按月汇总的Sql组

时间:2015-05-19 13:06:39

标签: sql group-by sql-server-2012

我使用下面的代码列出了本财政年度每个月(4月14日至3月15日)的计算结果:

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)

代码正在运行,以下面的格式提供每月数据:

Mth Yr n HES DataCompleteness

2014年4月49 48.5 101.03

我想在底部添加摘要总计,我通常会使用汇总执行此操作,但因为我在多个字段上进行分组,所以会在我的结果中添加重复行。

有解决方法吗?我使用的是SQL Server MS 2012

由于

2 个答案:

答案 0 :(得分:1)

$optParams = array( 'customer' => 'my_customer', 'userKey' => 'john@example.com' ); $results = $service->groups->listGroups($optParams); 分组,空分组:

GROUPING SETS

答案 1 :(得分: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