没看明白你的意思,根据你的结果退出来的写法。
E的最小值加上1等D的最大值则合并,select出来的却是组中的E的最大值和D的最小值
; with TestTable(A,B,C,D,E,F,G) AS(
select 'CF004','DZ','H','005','016',12,100 union all
select 'CF004','DZ','H','002','004',3,200 union all
select 'CF004','DZ','F','006','016',11,300 union all
select 'CF004','DZ','F','002','004',3,400 union all
select 'CF005','DZ','D','005','017',13,100 union all
select 'CF005','DZ','D','002','004',3,400
)
select A,B,C,min(D) as D,max(E) as E,sum(F) as F,sum(G) as G from (
select *,row_number()over(partition by A,B,C order by E DESC) as rn_E,row_number()over(partition by A,B,C order by D) as rn_D
,min(E)over(partition by A,B,C) as min_E,max(D)over(partition by A,B,C) as max_D
from TestTable
) as t
group by A,B,C,case when min_E+1-max_D=0 then '0' else convert(varchar(100),newid()) end
A B C D E F G
1 CF004 DZ F 006 016 11 300
2 CF004 DZ F 002 004 3 400
3 CF004 DZ H 002 016 15 300
4 CF005 DZ D 002 017 16 500