100分求教一个SQL查询的问题,盼达人指点
本帖最后由 x287634334 于 2012-08-21 05:28:17 编辑 假如我有这样一张表
person item qty
A b 15
A c 18
A d 21
B b 17
B c 23
B d 14
C d 19
C e 22
要怎样写SQL语句才能以下面这种形式显示?其中item的值是不确定的。
bcde
A 1518210
B1723140
C001922
[最优解释]
其中TableName为表名
declare @sql varchar(8000)
set @sql = 'select Person '
select @sql = @sql + ' , max(case item when ''' + item + ''' then qty else 0 end) [' + item + ']'
from (select distinct item from TableName) as a
set @sql = @sql + ' from TableName group by Person'
exec(@sql)
--通过动态构建@sql,得到如下脚本
select Person as Person ,
max(case item when 'b' then qty else 0 end) b,
max(case item when 'c' then qty else 0 end) c,
max(case item when 'd' then qty else 0 end) d,
max(case item when 'e' then qty else 0 end) d
from TableName
group by Person