2015-05-19 109 views
1

我使用下面的代碼列出該財政年度每個月計算的輸出(Apr14到Mar15):SQL組按月份和年份與彙總

select 
datename(month,arvd) Mth, 
year(arvd) Yr, 
count(submissionid) n, 
max(HES/12) HES, 
cast(count(submissionid)/max(HES/12)*100 as decimal(5,2)) DataCompleteness 

from PRIcache p 
left join (select distinct hsite, HES from hsite where hyear=2013) hs on 
hs.hSite = p.site 

where siteid=8 and arvd between '20140401' and '20150331' 

group by datename(month,arvd), datepart(month,arvd), year(arvd) 
order by year(arvd), datepart(month,arvd) 

運行代碼給我

第M YRñHES DataCompleteness


2014 49 48.5 101.03

012 4月:在下面的格式的每月數字

我想在底部添加彙總總計,我通常會在彙總時執行此操作,但由於我在多個字段上進行分組,因此會將重複行添加到我的結果中。

有沒有辦法解決這個問題?我使用SQL Server 2012 MS

感謝

+0

不要使用'BETWEEN'具有連續範圍的類型,[像日期/時間/時間戳(http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/ 19 /什麼-DO之間和最開發il-have-in-common.aspx)(特別是在SQL Server中)。 –

回答

1

集團通過GROUPING SETS空分組:

... 
Group by Grouping Sets((datename(month,arvd), datepart(month,arvd), year(arvd)),()) 
order by year(arvd), datepart(month,arvd) 
0

謝謝你的建議對分組集,我有一個子查詢,以獲得它們結合在一起輸出我需要:

Select isnull(Mth,'Total') Mth, 
    isnull(Yr,'9999') Yr, 
    sum(n) ActualSubmissions, 
    sum(HES) ExpectedSubmissions, 
    cast(avg(DataCompleteness) as decimal(5,2)) DataCompleteness 

from 

    (select  datename(month,arvd) Mth, 
       Month(arvd) MthSort, 
       Year(arvd) Yr, 
       count(submissionid) n, 
       HES/12 HES, 
       cast(count(submissionID)/(HES/12) as decimal(5,2)) DataCompleteness 
    from PRIcache p 
     left join hSite on p.site=hSite and hyear=2013 
    where siteid=8888 and arvd between '20140401' and '20150330' 
    group by datename(month,arvd), Month(arvd), year(arvd), HES) #datacomp 


group by Grouping sets ((Mth,Yr,MthSort),()) 

order by Yr, MthSort