由于我使用的是Union语句,因此我为每个单独的数据库中的每个城市返回了不同的行。我只想从每个数据库返回一行。但是如果我在我的%上使用SUM()函数,它会大大扭曲百分比。我可以在查询中做些什么来准确地从两个表中返回百分比,并且每个城市只返回一行?
Select City, Sum([Hospital In 50 Miles]), [% Where Hospital In 50 Miles]
FROM (
Select city, count(case when in50 = 'Yes' then hospID else null end) As [Hospital In 50 Miles],
CAST(COUNT(case when in50 = 'Yes' then hospID else null end)*1/Count(case when in50 is not null then in50 else null end) as decimal(10,4)) As [% Where Hospital In 50 Miles]
from database1
where in50 is not null
UNION ALL
Select city, count(case when in50 = 'Yes' then hospID else null end) As [Hospital In 50 Miles],
CAST(COUNT(case when in50 = 'Yes' then hospID else null end)*1/Count(case when in50 is not null then in50 else null end) as decimal(10,4)) As [% Where Hospital In 50 Miles]
from database2
where in50 is not null
) as
Group by city
答案 0 :(得分:1)
您不能平均SUM,您必须对组件求和并对它们求平均值。像这样:
Select City, Sum([Hospital In 50 Miles]),
Sum([Hospital In 50 Miles])/SUM([Hospitals]) AS [% Where Hospital In 50 Miles]
FROM (
Select city, count(case when in50 = 'Yes' then hospID else null end) As [Hospital In 50 Miles],
CAST(Count(case when in50 is not null then in50 else null end) as decimal(10,4)) As [Hospitals]
from database1
where in50 is not null
UNION ALL
Select city, count(case when in50 = 'Yes' then hospID else null end) As [Hospital In 50 Miles],
CAST(Count(case when in50 is not null then in50 else null end) as decimal(10,4)) As [Hospitals]
from database2
where in50 is not null
) as
Group by city
可能需要对输出进行一些额外的格式化,但这是基本结构。
答案 1 :(得分:1)
为什么不在每个子查询中添加一个总列,所以你有类似
的东西SELECT City,
In50 = COUNT(CASE WHEN In50 = 'Yes' THEN 1 END),
Total = COUNT(*)
FROM Database1
WHERE In50 IS NOT NULL
GROUP BY City
然后你的%计算只是SUM(In50) / SUM(Total)
:
SELECT City,
In50 = SUM(In50),
PercentIn50 = 1.0 * SUM(In50) / SUM(Total)
Total = SUM(Total)
FROM (
SELECT City,
In50 = COUNT(CASE WHEN In50 = 'Yes' THEN 1 END),
Total = COUNT(*)
FROM Database1
WHERE In50 IS NOT NULL
GROUP BY City
UNION ALL
SELECT City,
In50 = COUNT(CASE WHEN In50 = 'Yes' THEN 1 END),
Total = COUNT(*)
FROM Database2
WHERE In50 IS NOT NULL
GROUP BY City
) AS t
GROUP BY City;
N.B。我已经通过可能导致查询失败的子句添加了缺少的组,并删除了冗余检查,例如COUNT(CASE WHEN In50 IS NOT NULL THEN In50 ELSE NULL END)
- 这是没有必要的,因为你在where子句中已经有WHERE In50 IS NOT NULL