我有张A表,按条件汇总
我有张A表,按条件汇总
ID F2 F3 F4 F5
1 A03 A 5 XX
2 A02 B 3 XX
3 A03 B 2 XX
4 A04 C 5 XX
5 A02 B 6 XX
要求
按F2与F3汇总F4
条件
当F3=A 时 Sum(F4) <10 Group by F2,F3 小时,就给个相差数(sum(F4)与条件值的)
当F3=B 时 Sum(F4) <20 Group by F2,F3 ...................
当F3=C 时 sum(F4) <15 Group by F2,F3 ...................
怎么写SQL语句?
------解决方案--------------------select F2,F3,sum(F4),10-sum(F4) as cahzhi from A group by F2,F3 having sum(F4) <10 and F3= 'A '
select F2,F3,sum(F4),20-sum(F4) as cahzhi from A group by F2,F3 having sum(F4) <10 and F3= 'B '
select F2,F3,sum(F4),15-sum(F4) as cahzhi from A group by F2,F3 having sum(F4) <10 and F3= 'C '
------解决方案--------------------/*
是这样吗?
*/
declare @Test table (ID int, F2 varchar(3), F3 varchar(1), F4 int, F5 varchar(2))
insert @Test
select '1 ', 'A03 ', 'A ', '5 ', 'XX ' union all
select '1 ', 'A03 ', 'A ', '5 ', 'XX ' union all
select '1 ', 'A03 ', 'A ', '5 ', 'XX ' union all
select '2 ', 'A02 ', 'B ', '3 ', 'XX ' union all
select '3 ', 'A03 ', 'B ', '2 ', 'XX ' union all
select '4 ', 'A04 ', 'C ', '5 ', 'XX ' union all
select '5 ', 'A02 ', 'B ', '6 ', 'XX '
select F2, F3, sum(F4) - case F3
when 'A