初表如下:
年份    销量
2005   100
2006   200
2007   300写一段SQL语言,能显示这样一个表
年份  2005  2006  2007
销量  100   200   300

解决方案 »

  1.   

    ??
    case .. when ...
      

  2.   

    Use test
    Go
    Declare @1 Table([year] int,Qty int)
    Insert Into @1
    Select 2005,  100 Union All
    Select 2006,  200 Union All
    Select 2007,  300 Select * From 
    (Select '销量' As [年份],[Year],Qty From @1) P
    Pivot
    (SUM(Qty) For [Year] in([2005],[2006],[2007])) Pv/*
    年份   2005        2006        2007
    ---- ----------- ----------- -----------
    销量   100         200         300
    */
      

  3.   

    create table tb(nf int,xl int)
    insert into tb select 2005,100
    insert into tb select 2006,200
    insert into tb select 2007,300declare @sql varchar(8000)
    select @sql=isnull(@sql+',','')+'sum(case when nf='''+ltrim(nf)+''' then xl else 0 end ) as ['+ltrim(nf)+'年]'
    from tb group by nf
    exec('select '+@sql+' from tb')select 
    sum(case when nf='2005' then xl else 0 end ) as [2005年],
    sum(case when nf='2006' then xl else 0 end ) as [2006年],
    sum(case when nf='2007' then xl else 0 end ) as [2007年] 
    from tb100 200 300
      

  4.   

    select '销量' as 年份,
      max(case 年份 when 2005 then 销量 else 0 end) '2005',
      max(case 年份 when 2006 then 销量 else 0 end) '2006',
      max(case 年份 when 2007 then 销量 else 0 end) '2007'
    from tb
      

  5.   


    create table sss(年份 int,销量 int)
    insert into sss
    select 2005,100 union all
    select 2006,200 union all
    select 2007,300
    declare @sql varchar(8000),@sql1 varchar(8000)
    set @sql='select ''年份'''
    set @sql1='select ''销量'''
    select @sql=@sql+',['+ltrim(px)+']=max(case px when '+ltrim(px)+' then 年份 else 0 end)',
    @sql1=@sql1+',['+ltrim(px)+']=max(case px when '+ltrim(px)+' then 销量 else 0 end)'
    from (select px=(select count(1) from sss where 年份<=a.年份) from sss a)b
    set @sql=@sql+' from (select px=(select count(1) from sss where 年份<=a.年份),* from sss a)b '
    set @sql1=@sql1+' from (select px=(select count(1) from sss where 年份<=a.年份),* from sss a)b'
    exec(@sql+' union all '+@sql1)
      

  6.   

    楼主说的不是很明白,呵呵--sql server 2005 可以这样
    declare @t table (年份 int,销量 int)
    insert into @t
    select 2005,100 union all
    select 2006,200 union all
    select 2007,300;with
    t as(
    select '销量'as '年份',年份 as a,销量 as b from @t
    )
    select *
    from t
    pivot(
    max(b)
    for a 
    in([2005], [2006], [2007])
    )a