首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > VB Dotnet >

100分求教一个SQL查询的有关问题,盼达人指点

2012-12-21 
100分求教一个SQL查询的问题,盼达人指点本帖最后由 x287634334 于 2012-08-21 05:28:17 编辑假如我有这样

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

[其他解释]
你这属于竖表变横表,写个存储过程或自己写代码组织数据
[其他解释]
动态行转列。
[其他解释]
Oracle用decode
SQL case when 可以实现的,嘿嘿,需要写写SQL文试试的,慢慢调试,还不是很纠结

热点排行