表A,ID,名称,数量,金额
要求数量>500为 A类否则为B类,汇总A和B的金额1 零件 200 10000
2 材料 500 20000
3 配件 100 5000
4 油料 1000 80000结果:A类 300 15000
B类 1500 100000
select case when 数量>500 then 'A类' else 'B类' end as 类别,sum(金额)
from 表A
group by 什么呢?
要求数量>500为 A类否则为B类,汇总A和B的金额1 零件 200 10000
2 材料 500 20000
3 配件 100 5000
4 油料 1000 80000结果:A类 300 15000
B类 1500 100000
select case when 数量>500 then 'A类' else 'B类' end as 类别,sum(金额)
from 表A
group by 什么呢?
from 表A
group by case when 数量>500 then 'A类' else 'B类' end
from 表A
group by case when 数量>500 then 'A类' else 'B类' end
类别,sum(金额) as 金额
from
(select case when 数量>500 then 'A类' else 'B类' end as 类别,金额
from 表A)t
group by
类别
(ID int,名称 varchar(10),数量 int,金额 int)
insert #tba
select 1 ,'零件', 200, 10000 union all
select 2 ,'材料', 500, 20000 union all
select 3 ,'配件', 100, 5000 union all
select 4 ,'油料', 1000, 80000
select case when 数量>=500 then 'A类' else 'B类' end as 类别,sum(数量) as 数量_sum,sum(金额) 金额_sum
from #tba
group by case when 数量>=500 then 'A类' else 'B类' end类别 数量_sum 金额_sum
---- ----------- -----------
A类 1500 100000
B类 300 15000(2 行受影响)
insert tb
select 1 ,'零件', 200, 10000 union all
select 2 ,'材料', 500, 20000 union all
select 3 ,'配件', 100, 5000 union all
select 4 ,'油料', 1000, 80000 select case when 数量 >= 500 then 'A类' else 'B类' end 类别,
sum(数量) 数量,
sum(金额) 金额
from tb
group by case when 数量 >= 500 then 'A类' else 'B类' enddrop table tb/*
类别 数量 金额
---- ----------- -----------
A类 1500 100000
B类 300 15000(所影响的行数为 2 行)
*/
insert tb
select 1 ,'零件', 200, 10000 union all
select 2 ,'材料', 500, 20000 union all
select 3 ,'配件', 100, 5000 union all
select 4 ,'油料', 1000, 80000 select 'A类' 类,sum(数量) 数量,sum(金额) 金额 from tb where 数量<500
union all
select 'B类' 类,sum(数量) 数量,sum(金额) 金额 from tb where 数量>=500
类 数量 金额
---- ----------- -----------
A类 300 15000
B类 1500 100000(2 行受影响)
insert tb
select 1 ,'零件', 200, 10000 union all
select 2 ,'材料', 500, 20000 union all
select 3 ,'配件', 100, 5000 union all
select 4 ,'油料', 1000, 80000 select 'A类' 类,sum(数量) 数量,sum(金额) 金额 from tb where 数量<500
union all
select 'B类' 类,sum(数量) 数量,sum(金额) 金额 from tb where 数量>=500类 数量 金额
---- ----------- -----------
A类 300 15000
B类 1500 100000(2 行受影响)
group by a.类别
group by a.类别