sql行转列


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

仓库名称 商品名称 数量
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值