示例数据:
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)
取得预期结果的最佳方法是什么?(使用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
逻辑:当数据为‘20050301’时,如果数据为‘20050301’,则需要求和(A),如果日期是连续的(在这种情况下,为20050101-20050201-20050301);如果日期是连续的,则C>0 c=1000 (c>0)大于sum(a) (在本例中为,200501-20050601-20050701),当date=' 20050801‘c=1000 (c>0)时,则只需要在20050801年,以此类推。
发布于 2018-04-20 10:43:14
请尝试以下查询:
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
发布于 2018-04-20 10:22:11
对于按年计算的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
https://stackoverflow.com/questions/49939133
复制相似问题