sql行转列

来源:互联网 发布:中国食品药品数据查询 编辑:程序博客网 时间:2024/05/17 07:23

写一个存储过程,将表一按照表二的形式进行查询。

仓库名称 商品名称 数量
A
S001 12
A S002 17
A
S003 10
B S001 21
B
S002 5
B S003 0

C S001 100
C S002 11

C S003 25

(表一)


品名称 总库存 A B C
S001 133 12 21 100

S002 33 17 5 11
S003 35 10 0
25

(表二)

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
原创粉丝点击