SQL语句有点难的问题 ,超大难度的问题,

有一个商品货位表

他由一个主从表结构得到的数据。

货品基础资料表
货品编码, 货品名称
001 酒
002 烟

主表

仓库编号,仓库名称
1 一号仓库
2 2号仓库

从表

仓库编号(外键) 货品编码, 数量
1 001 3
1 002 5
2 001 6
2 001 1

要得到货位表的结构如下:
货品编码,货品名称,一号仓库,二号仓库
001 酒 3 7
002 烟 5 0

是不是非常难,如果要用临时表解决也可以
---------------------------------------------------------------

select t2.货品编码,t2.货品名称,一号仓库=isnull(sum(case t1.仓库编号 when 1 then 数量 else 0 end),0),
二号仓库=isnull(sum(case t1.仓库编号 when 1 then 数量 else 0 end),0)
from (select 货品编码,仓库编号,数量=sum(数量) from 从表 group by 货品编码,仓库编号)t1 right join 货品基础资料表 t2 on t1.货品编码=t2.货品编码

---------------------------------------------------------------

declare @intCount int,@DepotCount int,@SqlStr varchar(800)

select @DepotCount=(select count(仓库编号) from 仓库表)
select @intCount=1
select @SqlStr=''
while @intCount<=@DepotCount
begin
select @SqlStr=@SqlStr+',isnull(sum(case t1.仓库编号 when '+@intCount +' then 数量 else 0 end),0) as ' + (select 仓库名 from 仓库表 where 仓库编号=cast(@intCount as varchar))

select @intCount=@intCount+1
end
select @SqlStr='select t2.货品编码,t2.货品名称'+@SqlStr + 'from (select 货品编码,仓库编号,数量=sum(数量) from 从表 group by 货品编码,仓库编号)t1 right join 货品基础资料表 t2 on t1.货品编码=t2.货品编码'

exec(@SqlStr)
---------------------------------------------------------------

少了group by :

declare @SqlStr varchar(7000)

set @SqlStr=''
select @SqlStr=@SqlStr+'isnull(sum(case t1.仓库编号 when '+cast(仓库编号 as varchar(10)) +' then 数量 else 0 end),0) as ' + rtrim(仓库名称)+',' from 仓库表 order by 仓库编号

select @SqlStr='select t2.货品编码,t2.货品名称,'+@SqlStr + 'isnull(sum(t1.数量),0) as 合计 from (select 货品编码,仓库编号,数量=sum(数量) from 从表 group by 货品编码,仓库编号) t1 right join 货品基础资料表 t2 on t1.货品编码=t2.货品编码 group by t2.货品编码,t2.货品名称'

exec(@SqlStr)

你的语句:
select t2.cbh,t2.zwmz,
仓库1=isnull(sum(case t1.ckbh when 1 then number else 0 end),0),
仓库2=isnull(sum(case t1.ckbh when 2 then number else 0 end),0),
仓库3=isnull(sum(case t1.ckbh when 3 then number else 0 end),0)
From (select cbh,ckbh, number=sum(number) from fkcb group by cbh,ckbh) t1
right join jbxx t2 on t1.cbh=t2.cbh
group by t2.cbh,t2.zwmz

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus