27,579
社区成员
发帖
与我相关
我的任务
分享
create table tb(仓库名称 varchar(10),商品名称 varchar(10),数量 int)
insert into tb values('A', 'S001', 12)
insert into tb values('A', 'S002', 17)
insert into tb values('A', 'S003', 10)
insert into tb values('B', 'S001', 21)
insert into tb values('B', 'S002', 5)
insert into tb values('B', 'S003', 0)
insert into tb values('C', 'S001', 100)
insert into tb values('C', 'S002', 11)
insert into tb values('C', 'S003', 25)
go
--如果只有A,B,C,则使用静态SQL。
select 商品名称,
sum(数量) 总库存,
sum(case 仓库名称 when 'A' then 数量 else 0 end) [A],
sum(case 仓库名称 when 'B' then 数量 else 0 end) [B],
sum(case 仓库名称 when 'C' then 数量 else 0 end) [C]
from tb
group by 商品名称
/*
商品名称 总库存 A B C
---------- ----------- ----------- ----------- -----------
S001 133 12 21 100
S002 33 17 5 11
S003 35 10 0 25
(所影响的行数为 3 行)
*/
--如果不止A,B,C,则用动态SQL
declare @sql varchar(8000)
set @sql = 'select 商品名称 , sum(数量) 总库存 '
select @sql = @sql + ' , sum(case 仓库名称 when ''' + 仓库名称 + ''' then 数量 else 0 end) [' + 仓库名称 + ']'
from (select distinct 仓库名称 from tb) as a
set @sql = @sql + ' from tb group by 商品名称'
exec(@sql)
/*
商品名称 总库存 A B C
---------- ----------- ----------- ----------- -----------
S001 133 12 21 100
S002 33 17 5 11
S003 35 10 0 25
(所影响的行数为 3 行)
*/
drop table tb
--drop table tb
create table tb(a varchar(10), b varchar(20),c int)
go
insert into tb select
'A','S001',12 union all select
'A','S002',17 union all select
'A','S003',10 union all select
'B','S001',21 union all select
'B','S002',5 union all select
'B','S003',0 union all select
'C','S001',100 union all select
'C','S002',11 union all select
'C','S003',25
select B,A1,B1,C1,A1+B1+C1 as [总库存]
from (
select B,
sum(case A when 'A' then c else 0 end) as 'A1',
sum(case A when 'B' then c else 0 end) as 'B1',
sum(case A when 'C' then c else 0 end) as 'C1'
from tb
Group by B
) tb
B A1 B1 C1 总库存
-------------------- ----------- ----------- ----------- -----------
S001 12 21 100 133
S002 17 5 11 33
S003 10 0 25 35
(3 行受影响)