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

x287634334 2012-08-21 05:23:05
假如我有这样一张表
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的值是不确定的。

  b c d e
A 15 18 21 0
B 17 23 14 0
C 0 0 19 22
...全文
65 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
lys83363110 2012-08-21
  • 打赏
  • 举报
回复
Oracle用decode
SQL case when 可以实现的,嘿嘿,需要写写SQL文试试的,慢慢调试,还不是很纠结
快溜 2012-08-21
  • 打赏
  • 举报
回复
动态行转列。
bdmh 2012-08-21
  • 打赏
  • 举报
回复
你这属于竖表变横表,写个存储过程或自己写代码组织数据
  • 打赏
  • 举报
回复
其中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

16,556

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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