问题描述
SELECT County,Result1,COUNT(Result1) AS Result1Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
GROUP BY County,Result1
ORDER BY County;
SELECT County,Result2,COUNT(Result2) AS Result2Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
AND Result2 <> 'NULL'
GROUP BY County,Result2
ORDER BY County;
SELECT County,Result3,COUNT(Result3) AS Result3Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
AND Result3 <> 'NULL'
GROUP BY County,Result3
ORDER BY County;
我希望输出如下所示:
County Result Totals
-----------------------------------
Allegany Car Services 2
Richmond Car Services 3
Lynchberg House Services 5
Charlotte Car Services 12
Charlotte House Services 2
northHampton Car Serivces 6
northHampton House Services 8
结果 1、2 和 3 是具有相同信息的下拉框。
解决方法
如果列总计代表 resulttotal 的国家明智的结果明智的总和,那么您的查询将是:
select Country,Result,sum(Result1Total) Totals
from (
SELECT County,Result1 Result,Count(Result1) AS Result1Total
FROM MainData
WHERE (((Date) Between '01/01/2020' And '01/30/2020'))
GROUP BY County,Result1
union all
SELECT County,Result2,Count(Result2) AS Result2Total
FROM MainData
WHERE (((Date) Between '01/01/2020' And '01/30/2020'))
AND Result2 <> 'NULL'
GROUP BY County,Result2
union all
SELECT County,Result3,Count(Result3) AS Result3Total
FROM MainData
WHERE (((Date) Between '01/01/2020' And '01/30/2020'))
AND Result3 <> 'NULL'
GROUP BY County,Result3
)
group by County,Result
ORDER BY County;
,
看起来 GROUPING SETS
在这里会派上用场:
SELECT
County,ISNULL(ISNULL(Result1,Result2),Result3) AS Result,COUNT(Result1) AS Result1Total
FROM MainData
WHERE (((Date) BETWEEN '01/01/2020' AND '01/30/2020'))
GROUP BY GROUPING SETS (
(County,Result1),(County,Result3)
)
ORDER BY County;
如果 Result
列可以为空,那么您需要一个更复杂的表达式:
CASE WHEN GROUPING(Result1) = 0 THEN Result1
WHEN GROUPING(Result1) = 0 THEN Result2
ELSE Result3
END AS Result,