按州和季度查询总计。试图在所有县的底部添加总计,并为所有县增加季度总数。
添加了汇总代码,但它没有返回任何内容,表格相同,没有总计
select isnull(convert(VARCHAR,DCOUNTYNAME),'GRAND TOTAL') AS County,
Year(DDATE) as Year, ---selects year value for total and quarter totals
count(*) as Total, ---counts year totals
sum(case when DATEPART(q, DDATE)=1 then 1 else 0 end) as Q1,
sum(case when DATEPART(q, DDATE)=2 then 1 else 0 end) as Q2,
sum(case when DATEPART(q, DDATE)=3 then 1 else 0 end) as Q3,
sum(case when DATEPART(q, DDATE)=4 then 1 else 0 end) as Q4
into #tfinal
from Cert
where FLAG = 'o' and year(cast(ddDate as date)) ='2013'
group by DCOUNTYNAME,
Year(DDATE) with rollup
现在结果
County Year Total Q1 Q2 Q3 Q4
IMPERIAL 2013 129 5 20 100 4
FRESNO 2013 67 19 16 15 17
SAN DIEGO 2013 408 70 66 94 194
希望得到的结果
County Year Total Q1 Q2 Q3 Q4
IMPERIAL 2013 129 5 20 100 4
FRESNO 2013 67 19 16 15 17
SAN DIEGO 2013 408 70 66 94 194
Grand Total 595 94 106 209 215
答案 0 :(得分:2)
听起来,根据评论,您可能已经取得了您所寻找的结果。这是另一种方法,此方法允许您明确控制总计的显示方式。
With CTE as (
--Insert Existing query without rollup here
)
Select * From CTE
Union All
Select 'Grand Total' as County
, null as Year
, SUM(Total) as Total
, SUM(Q1) as Q1
, SUM(Q2) as Q2
, SUM(Q3) as Q3
, SUM(Q4) as Q4
From CTE