当前位置: 代码迷 >> ASP.NET >> sql的有关问题
  详细解决方案

sql的有关问题

热度:9586   发布时间:2013-02-25 00:00:00.0
sql的问题
一个group   by语句结果是
名称       数量
a               12
b               11
c               23
d               33
相让查询结果这样显示如何写SQL语句。
a       b         c         d
12     11       23       33


------解决方案--------------------------------------------------------
SELECT a = case when 名称 = 'a ' then 数量 else 0 end,
b = case when 名称 = 'b ' then 数量 else 0 end,
c = case when 名称 = 'c ' then 数量 else 0 end,
d = case when 名称 = 'd ' then 数量 else 0 end
From (group by语句结果)
------解决方案--------------------------------------------------------
select 名称,
数量=sum(case when 名称= 'a ' then 数量 else 0 end),
数量=sum(case when 名称= 'b ' then 数量 else 0 end),
数量=sum(case when 名称= 'c ' then 数量 else 0 end),
数量=sum(case when 名称= 'd ' then 数量 else 0 end)
from 表名
group by 名称

------解决方案--------------------------------------------------------
那就写个存储过程,用游标解决.
------解决方案--------------------------------------------------------

declare @s varchar(8000)
set @s = ' '
select @s = @s
+ ', '+名称+ ' = max(case 名称 when ' ' '+名称+ ' ' ' then 数量 else 0 end ) '
from tb
set @s= stuff(@s,1,1, ' ')
exec( 'select '+@s+ 'from tb group by 名称 ')
------解决方案--------------------------------------------------------
a b c d .....数量是不定的

行不固定不太好弄..

  相关解决方案