日期:2014-05-17  浏览次数:20479 次

求大神帮忙~~~~
我在数据库中查询到的数据是这样的形式:
订单   存货名称  工序名  数量
0001    aaaa      a       1000
0001    aaaa      b       2000
0001    aaaa      c       3000

怎样用SQL语句将其改成这样的形式:

订单   存货名称   a         b      c
0001    aaaa    1000  2000  3000
sql 数据库

------解决方案--------------------
工序名 相同 求合计时用把 max 改为sum
use tempdb
go
if OBJECT_ID('Tempdb..#1') is not null
drop table #1
Create table #1(订单 varchar(10),  存货名称 varchar(10),  工序名 varchar(10),  数量 int)
insert into #1
select '0001',    'aaaa',      'a',       1000 union all
select '0001',    'aaaa',      'b',       2000 union all
select '0001',    'aaaa',      'c',       3000
go

declare @sql nvarchar(2000)
set @sql='select 订单,存货名称'
select @sql=@sql+','+QUOTENAME(工序名)+'=max(case when [工序名]='+QUOTENAME(工序名,'''')+' then 数量 else 0 end)'
from #1 group by 工序名
exec(@sql+' from #1 group by 订单,存货名称')
/*
订单 存货名称 a b c
0001 aaaa 1000 2000 3000
*/

------解决方案--------------------
select 订单,存货名称,max(case when [工序名]='a' then 数量 else 0 end) as [a],max(case when [工序名]='b' then 数量 else 0 end) as [b],max(case when [工序名]='c' then 数量 else 0 end) as [c] from tb group by 订单,存货名称