1   2008-1-1
1   2008-2-1
1   2008-3-1
2   2008-2-1
2   2008-3-1
3   2008-3-1要交叉表出来成序号 2008年1月  2008年2月 2008年3月
1    2008-1-1  2008-2-1 2008-3-1
2              2008-2-1 2008-3-1
3                       2008-3-1
如何实现

解决方案 »

  1.   

    ------------------------------------
    -- Author:Flystone 
    -- Version:V1.001  
    -- Date:2008-08-05 22:20:24
    -------------------------------------- Test Data: ta
    If object_id('ta') is not null 
        Drop table ta
    Go
    Create table ta(id int,datecol smalldatetime)
    Go
    Insert into ta
    select 1,'2008-1-1' union all
    select 1,'2008-2-1' union all
    select 1,'2008-3-1' union all
    select 2,'2008-2-1' union all
    select 2,'2008-3-1' union all
    select 3,'2008-3-1' 
    Go
    --Start
    declare @s varchar(1000)
    select @s = isnull(@s+',','') + '['+d+'] 
    = max(case when datepart(mm,datecol) = '+ right(d,2) + ' then datecol end)'
    from (select distinct left(convert(varchar(10),datecol,120),7) as d from ta) a
    exec('select id,'+ @s+ ' from ta group by id')
    --Result:
    /*
    id          2008-01                                                2008-02                                                2008-03                                                
    ----------- ------------------------------------------------------ ------------------------------------------------------ ------------------------------------------------------ 
    1           2008-01-01 00:00:00                                    2008-02-01 00:00:00                                    2008-03-01 00:00:00
    2           NULL                                                   2008-02-01 00:00:00                                    2008-03-01 00:00:00
    3           NULL                                                   NULL                                                   2008-03-01 00:00:00警告: 聚合或其它 SET 操作消除了空值。
    */
    --End 
      

  2.   

    通过这个问题,自己也明白了不少,感谢楼主,感谢2楼.动态SQL真是无穷功能呀