读书人

这个查询语句如何写

发布时间: 2012-01-30 21:15:58 作者: rapoo

这个查询语句怎么写?
我有一个这样的表格,如下:

物料 仓库 数量
101 A 200
101 C 100
102 A 502
102 B 200
102 C 100
103 C 200
104 A 100

我想通过查询变成如下格式:
物料 仓库A数量 仓库B数量 仓库C数量
101 200 0 100
102 502 200 100
103 0 0 200
104 100 0 0

请问我这个查询应该怎样写?
我试过下面这样写,
select a.物料,a.库存 as 仓库A数量,b.仓库B数量,c.仓库c数量 from 表,
(select 物料,仓库 as 仓库B数量 from 表 where 仓库= 'b ') b,
(select 物料,仓库 as 仓库B数量 from 表 where 仓库= 'c ') c
where a.仓库= 'a ' and a.物料=b.物料 and a.物料=c.物料

这样写后就漏掉如只有一个仓库有库存,或只有两个仓库有库存的。只能查询出三个仓库都有库存的。
有没有办法把三个仓库的物料,只要有一个仓库有库存,都显示出来。?



[解决办法]
create table 表(物料 int,仓库 char(1),数量 int)
insert into 表
select 101, 'A ',200
union all select 101, 'C ',100
union all select 102, 'A ',502
union all select 102, 'B ',200
union all select 102, 'C ',100
union all select 103, 'C ',200
union all select 104, 'A ',100

select 物料,
仓库A数量 = sum(case when 仓库 = 'A ' then 数量 else 0 end),
仓库B数量 = sum(case when 仓库 = 'B ' then 数量 else 0 end),
仓库C数量 = sum(case when 仓库 = 'C ' then 数量 else 0 end)
from 表
group by 物料
/*
物料 仓库A数量 仓库B数量 仓库C数量
----------- ----------- ----------- -----------
101 200 0 100
102 502 200 100
103 0 0 200
104 100 0 0

(所影响的行数为 4 行)
*/
------解决方案--------------------



--如果仓库是固定的
Select
物料,
SUM(Case 仓库 When 'A ' Then 数量 Else 0 End) As 仓库A数量,
SUM(Case 仓库 When 'B ' Then 数量 Else 0 End) As 仓库B数量,
SUM(Case 仓库 When 'C ' Then 数量 Else 0 End) As 仓库C数量
From

Group By
物料
[解决办法]
--如果仓库不是固定的
Declare @S Varchar(8000)
Select @S = ' Select 物料 '
Select @S = @S + ' , SUM(Case 仓库 When ' ' ' + 仓库 + ' ' ' Then 数量 Else 0 End) As 仓库 ' + 仓库 + '数量 '
From 表 Group By 仓库
Select @S = @S + ' From 表 Group By 物料 '
EXEC(@S)
[解决办法]
动态写法

declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+ ',max(case when 仓库 = ' ' '+仓库+ ' ' ' then 数量 else 0 end) as ' '仓库 '+仓库+ '数量 ' ' '
from (select distinct 仓库 from 表)t order by 仓库
exec ( 'select 物料 '+@sql+ ' from 表 group by 物料 ')

读书人网 >SQL Server

热点推荐