2015-09-24 247 views
3

我遇到了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 

回答

2

有兩件事情你希望看到每一種做法:保險公司的數量,如果有的話,以及子計數的數量,如果有的話。

問題是,一旦你將兩個其他表連接到實踐表中,你將得到的記錄相乘(例如1次練習2 ptc和3 ptp 6次記錄)。

最簡單的方式得到你想要的是不是加入所有,但使用子查詢在SELECT子句什麼:

select 
    Name, 
    (
    select count(*) 
    from PracticesToInsuranceCompanies ptc 
    where ptc.PracticeID = p.PracticeID 
) as NumberInsuranceCompanies, 
    (
    select isnull(sum(SubCount), 0) 
    from PracticesToInsurancePlans ptp 
    where ptp.PracticeID = p.PracticeID 
) as SubCount 
from Practices p; 
+0

這工作完美! – optionsix

1

group by刪除subcountselect子句中使用subcountsum

select p.Name, 
    COUNT(ptc.InsuranceCompanyID) as NumberInsuranceCompanies, 
    sum(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 
    order by p.Name asc 
+0

以及它現在肯定是聚合的行,但計數了。我得到的新(單一)返回行是:練習1 4 30.看起來,如果這是您的完整查詢,那麼您根本不需要「PracticesToInsuranceCompanies」表,而是將保險公司的數量加倍並使用SubCounts – optionsix

+0

。 –

+0

看看你編輯的版本是否是你所需要的 –

相關問題