表数据如下:
年份   月份    收入
2011   1月       200
2011   2月       300
2011   3月       500
2012   1月       600
2012   2月       700要求查询结果如下:
年份  1月  2月   3月
2011  200  300   500
2012  600  700   NULL谢谢!

解决方案 »

  1.   

    select 年份,1月=isnull(sum(case 月份 when 1月 then 收入 end),0),
       2月=isnull(sum(case 月份 when 1月 then 收入 end),0),
       3月=isnull(sum(case 月份 when 3月 then 收入 end),0)
       from 表 
       group by 年份
    没测试。你试试
      

  2.   

    CREATE TABLE Test20120522
    (年份 int, 月份 varchar(50), 收入 int)INSERT INTO Test20120522
    SELECT 2011, '1月', 200
    UNION 
    SELECT 2011, '2月', 300
    UNION
    SELECT 2011, '3月', 500
    UNION
    SELECT 2012, '1月', 600
    UNION
    SELECT 2012, '2月', 700--- sql 2000SELECT 年份, min(case when 月份 = '1月' then 收入 else null end) as '1月',
    min(CASE WHEN 月份 = '2月' then 收入 else NULL end) as '2月',
    min(CASE WHEN 月份 = '3月' then 收入 else NULL end) as '3月'
    FROM test20120522 GROUP BY 年份--- sql 2005SELECT * FROM test20120522 PIVOT(sum(收入) for 月份 in ([1月], [2月], [3月])
      

  3.   

    参考这个帖子 http://topic.csdn.net/u/20080614/17/22e73f33-f071-46dc-b9bf-321204b1656f.html
      

  4.   

    --给你提供一种方法,适合不固定列的行列转换create  table t(年份 varchar(20), 月份 varchar(20), 收入 float)
    insert into t 
    select '2011','1月',200 union all
    select '2011','2月',300 union all
    select '2011','3月',500 union all
    select '2012','1月',600 union all
    select '2012','2月',700--select * From @tdeclare @sql varchar(8000)
    set @sql='select 年份'
    select @sql=@sql+ ',max(case 月份 when '''+月份+''' then 收入 end) as ['+月份+']' from (select distinct 月份 from t) as A
    set @sql=@sql+' from t group by 年份 order by 年份'exec (@sql)
    drop table t
    /*
    年份    1月     2月     3月
    ------ ------ ------ ------
    2011   200    300    500
    2012   600    700    null
    (2 个数据列受到影响)
    */