我遇到了SQL查詢問題。我有一個鏈接在一起的幾個表,我想組/彙總的回報,使他們有意義(我可怕在SQL分組)在sql查詢中對數據進行分組以聚合行
這裏是我的表結構與測試數據:
表InsuranceCompanies
(InsuranceCompanyID,公司名稱)
1 InsuranceCompany1
2 InsuranceCompany2
表InsurancePlans
(InsurancePlanID,PlanName)
1 InsurancePlan1
2 InsurancePlan2
表Practices
(PracticeID,PracticeName)
1 Practice1
表PracticesToInsuranceCompanies
(PracticeID,InsuranceCompanyID)
1 1
1 2
表PracticesToInsurancePlans
(PracticeID,InsurancePlanID,SubCount)
1 1 5
1 2 10
這是我的當前查詢:
select
p.Name,
COUNT(ptc.InsuranceCompanyID) as NumberInsuranceCompanies,
isnull(ptp.SubCount), 0) as SubCount
from
Practices p
left outer join
PracticesToInsuranceCompanies ptc on ptc.PracticeID = p.PracticeID
left outer join
PracticesToInsurancePlans ptp on ptp.PracticeID = p.PracticeID
group by
p.Name, ptp.SubCount
order by
p.Name asc
這裏是當前結果集:
RESULTS (PracticeName, NumberInsuranceCompanies, SubCount)
Practice1 2 10
Practice1 2 5
在上面的例子中,預期的結果是有一個單列,因爲僅存在一個返回實踐。這個練習有兩個與它相關的計劃,一個子計數爲10,一個子計數爲5,我只需要將該行聚合成一行,並將子計數作爲總和添加。保險公司的數量只是與之相關的數量。
INTENDED RESULTS
Practice1 2 15
這工作完美! – optionsix