SQL Server:使用CTE对年份数据进行分组

时间:2018-04-20 10:05:28

标签: sql-server group-by

示例数据:

create table #temp
(
    dateRef date,
    a float,
    b float,
    c float  
)

insert into #temp (dateRef, a, b, c) values ('20050101',1000,500,0)
insert into #temp (dateRef, a, b, c) values ('20050201',1000,1000,0)
insert into #temp (dateRef, a, b, c) values ('20050301',4000,4000,3000)
insert into #temp (dateRef, a, b, c) values ('20050401',2000,2000,1000)
insert into #temp (dateRef, a, b, c) values ('20050501',1000,2000,0)
insert into #temp (dateRef, a, b, c) values ('20050601',2000,2000,0)
insert into #temp (dateRef, a, b, c) values ('20050701',2000,2000,1000)
insert into #temp (dateRef, a, b, c) values ('20050801',2000,2000,1000)
--- 
insert into #temp (dateRef, a, b, c) values ('20060301',1000,1000,0)
insert into #temp (dateRef, a, b, c) values ('20060601',1000,1000,0)
insert into #temp (dateRef, a, b, c) values ('20060701',2000,2000,0)
insert into #temp (dateRef, a, b, c) values ('20060801',2000,2000,1000)
---
insert into #temp (dateRef, a, b, c) values ('20070101',1000,1000,0)

获得此预期结果的最佳方法是什么? (使用SQL Server 2012)

DateRef         a       b           c
----------------------------------------    
--- 20050301    6000    5500        3000    
--- 20050401    2000    2000        1000
--- 20050701    5000    6000        1000    
--- 20050801    2000    2000        1000    
--- 20060801    6000    6000        1000    

逻辑: 当C> 0,例如:当data ='20050301',c = 3000(c> 0)时,如果日期是连续的,则需要总和(a)(在这种情况下,它们是,当数据= 20050701 c = 1000(c> 0)时,如果日期是连续的(在这种情况下它们是,20050501-20050601-20050701),则数据= 20050701 c = 1000(c> 0),当date ='20050801'c时= 1000(c> 0)然后我需要总和(a)在这种情况下只有年20050801等等

2 个答案:

答案 0 :(得分:1)

尝试此查询:

select
    dateRef = max(dateRef), a = sum(a), b = sum(b), c = sum(c)
from (
    select 
        *, rn = datediff(mm, '19000101', dateRef) - row_number() over (order by dateRef)
        , grp = isnull(sum(iif(c > 0, 1, 0)) over (order by dateRef rows between unbounded preceding and 1 preceding), 0)
    from 
        #temp
) t
group by rn, grp
having sum(c) > 0

在查询中使用两列进行分组。 rn - 查找连续的行grp - 对行进行分组,其中c> 0,前面的行,其中c = 0。

输出

dateRef     a       b       c
---------------------------------
2005-03-01  6000    5500    3000
2005-04-01  2000    2000    1000
2005-07-01  5000    6000    1000
2005-08-01  2000    2000    1000
2006-08-01  5000    5000    1000

答案 1 :(得分:0)

对于Grouping年的数据,我们可以尝试一下 -

select
    year(dateref) as year,
    sum(a) as a,
    sum(b) as b,
    sum(c) as c
from #temp
group by year(dateref)

输出 -

year    a       b       c
2005    15000   15500   6000
2006    6000    6000    1000
2007    1000    1000    0