这个查询语句怎么写?

wingedsteed 2007-08-23 10:38:20
我有一个这样的表格,如下:

物料 仓库 数量
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.物料

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

...全文
186 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wingedsteed 2007-08-23
  • 打赏
  • 举报
回复
谢谢各位的热心帮助,按照“paoluo(一天到晚游泳的鱼(學習.NET中)) () ”的办法解决了。
gahade 2007-08-23
  • 打赏
  • 举报
回复
动态写法

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 物料')
paoluo 2007-08-23
  • 打赏
  • 举报
回复
--如果仓库不是固定的
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)
paoluo 2007-08-23
  • 打赏
  • 举报
回复

--如果仓库是固定的
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
物料
gahade 2007-08-23
  • 打赏
  • 举报
回复
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 行)
*/

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧