各位老大帮忙!急!!!
--表结构
create table stock
(
aid varchar(2),--商品
sl decimal(9,3),--库存数量
ck varchar(2)--仓库编号
primary key
(aid,ck)
)
--测试数据
insert into stock values( '01 ',1, '01 ')
insert into stock values( '01 ',1, '02 ')
insert into stock values( '01 ',1, '03 ')
insert into stock values( '01 ',1, '04 ')
insert into stock values( '02 ',1, '01 ')
insert into stock values( '02 ',1, '02 ')
insert into stock values( '02 ',1, '03 ')
insert into stock values( '03 ',1, '01 ')
insert into stock values( '03 ',1, '02 ')
insert into stock values( '03 ',1, '03 ')
--所有的非重复仓库
--select distinct ck from stock
--数据
--select * from stock
--生成如下格式的表
aid 01 02 03 04
01 1 1 1 1
02 1 1 1 0
03 1 1 1 0
--其中“01 02 03 04”的数量不定,表中商品01在仓库04中有1个
--商品02,03在04仓库中没有则为0
------解决方案----------------------如果ck固定,则用以下SQL:
select
aid,
[01]=sum(case ck when '01 ' then sl else 0 end),
[02]=sum(case ck when '02 ' then sl else 0 end),
[03]=sum(case ck when '03 ' then sl else 0 end),
[04]=sum(case ck when '04 ' then sl else 0 end)
from
stock
group by
aid
--如果ck不固定,则用以下SQL:
declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+ ',[ '+ck+ ']=sum(case ck when ' ' '+ck+ ' ' ' then sl else 0 end) ' from stock group by ck
set @sql= 'select aid '+@sql+ ' from stock group by aid '
exec(@sql)
go
------解决方案----------------------动态
declare @s varchar(2000)
set @s= 'select aid '
select @s=@s+ ',[ '+ck+ ']=sum(case when ck= ' ' '+ck+ ' ' ' then 1 else 0 end) '
from stock
group by ck
set @s=@s+ ' from stock group by aid '
exec(@s)