我遇到SQL查询问题。我有一些链接在一起的表,我正在尝试对返回进行分组/聚合以使它们有意义(我在SQL中分组时很糟糕)
以下是包含测试数据的表格结构:
表InsuranceCompanies
(InsuranceCompanyID,CompanyName)
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
在上面的示例中,INTENDED结果是一行,因为只返回一个Practice。该实践有两个与之关联的计划,一个子计数为10,一个子计数为5,我只需将该行聚合成一行,并将SubCount添加为总和。保险公司的数量只是与之相关的数量。
INTENDED RESULTS
Practice1 2 15
答案 0 :(得分: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;
答案 1 :(得分:1)
从subcount
移除group by
并使用sum
条款subcount
上的select
。
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