一个group by语句结果是
名称   数量
a       12
b       11
c       23
d       33
相让查询结果这样显示如何写SQL语句。
a   b    c    d
12  11   23   33

解决方案 »

  1.   

    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语句结果)
      

  2.   

    a b c d .....数量是不定的
      

  3.   

    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 名称
      

  4.   


    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 名称')
      

  5.   

    1)简单的行转列问题:示例表:id  sid           course  result1   2005001 语文     80.0
    2   2005001 数学     90.0
    3   2005001 英语     80.0
    4   2005002 语文     56.0
    5   2005002 数学     69.0
    6   2005002 英语     89.0执行select sid,语文=isnull(sum(case course when '语文' then result end),0),
       数学=isnull(sum(case course when '数学' then result end),0),
       英语=isnull(sum(case course when '英语' then result end),0)
       from result 
       group by sid
       order by sid 得出结果sid           语文 数学 英语 2005001 80.0  90.0  80.0
    2005002 56.0  69.0  89.0
      

  6.   

    a b c d .....数量是不定的行不固定不太好弄..