原表:
字段: xmbh    nd    tz
        23    2002   100
        23    2003   200
        23    2004   300
        23    2005   400
        23    2006   500
想得到下面这个表:
字段:xmbh    2004年之前   2005年   2006年
       23       600         400      500  
说明:2004年之前的统计怎么来实现?
      字段2004年之前   2005年   2006年应该是根据当年的时间来定的
比如:今年时间是2008 ,那么字段就应该是:
      2006年之前   2007年   2008年
如何解决啊?

解决方案 »

  1.   

    2004年之前的统计怎么来实现?
    select xmbh,sum(tz) from t where nd<='2004' group by xmbh 然后再跟其他的join吧
      

  2.   

    create table test
    (
    xmbh int,
    nd int,
    tz int
    )
    insert into test
    select 23,2002,100 union all
    select 23,2003,200 union all
    select 23,2004,300 union all
    select 23,2005,400 union all
    select 23,2006,500 union all
    select 23,2005,200 union all
    select 24,2006,300declare @year int
    declare @sql varchar(8000)
    select @year=datepart(year,getdate())select @sql=
    'select xmbh,sum(case when nd<='+rtrim(@year-2)+' then tz else 0 end) as ['+rtrim(@year-2)+'之前],
    sum(case when nd='+rtrim(@year-1)+' then tz else 0 end) as ['+rtrim(@year-1)+'],
    sum(case when nd='+rtrim(@year)+' then tz else 0 end) as ['+rtrim(@year)+']
    from test group by xmbh'exec (@sql)
    go
    drop table test/*
    xmbh        2004之前      2005        2006        
    ----------- ----------- ----------- ----------- 
    23          600         600         500
    24          0           0           300
    */
      

  3.   

    --with wrong datacreate table test
    (
    xmbh int,
    nd int,
    tz int
    )
    insert into test
    select 23,2002,100 union all
    select 23,2003,200 union all
    select 23,2004,300 union all
    select 23,2005,400 union all
    select 23,2006,500 union all
    select 24,2005,200 union all
    select 24,2006,300declare @year int
    declare @sql varchar(8000)
    select @year=datepart(year,getdate())select @sql=
    'select xmbh,sum(case when nd<='+rtrim(@year-2)+' then tz else 0 end) as ['+rtrim(@year-2)+'之前],
    sum(case when nd='+rtrim(@year-1)+' then tz else 0 end) as ['+rtrim(@year-1)+'],
    sum(case when nd='+rtrim(@year)+' then tz else 0 end) as ['+rtrim(@year)+']
    from test group by xmbh'exec (@sql)
    go
    drop table test/*xmbh        2004之前      2005        2006        
    ----------- ----------- ----------- ----------- 
    23          600         400         500
    24          0           200         300
    */