数据中数据,数据库中有N行数据,举例四行 如下:
   a          b      c       d 
123456        1      1       1
123456        1      2       2
123456        1      2       3
1234567       1      1       1
1234567       1      2       2查询后结果,达到效果:
   a          b      c1      d1   c2   d2   c3     d3
123456        1      1       1    2    2    2      3
1234567       1      1       1    2    2    null   nulla和b一样的显示在一行,c和d顺序排列下去,可能会出现c4和d4……cn和dn 没有数据的用null代替。
请坛子里高手 大侠帮忙,谢谢!小弟分不多,见谅!SQL数据库

解决方案 »

  1.   


    create table ora
    (a varchar(10), b int, c int, d  int)insert into ora
    select '123456', 1, 1, 1 union all
    select '123456', 1, 2, 2 union all
    select '123456', 1, 2, 3 union all
    select '1234567', 1, 1, 1 union all
    select '1234567', 1, 2, 2select * from ora/*
    a          b           c           d
    ---------- ----------- ----------- -----------
    123456     1           1           1
    123456     1           2           2
    123456     1           2           3
    1234567    1           1           1
    1234567    1           2           2(5 row(s) affected)
    */
    declare @tsql varchar(6000)
    select @tsql='select t.a,t.b,'select @tsql=@tsql
                 +'max(case when rn='+rtrim(rn)+' then c else null end) ''c'+rtrim(rn)+''', '
                 +'max(case when rn='+rtrim(rn)+' then d else null end) ''d'+rtrim(rn)+''', '
     from (select distinct row_number() over(partition by a order by getdate()) 'rn'
           from ora) tselect @tsql=left(@tsql,len(@tsql)-1)+'
     from (select a,b,c,d,row_number() over(partition by a order by getdate()) ''rn''
           from ora) t
     group by t.a,t.b 'exec(@tsql)/*
    a          b           c1          d1          c2          d2          c3          d3
    ---------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
    123456     1           1           1           2           2           2           3
    1234567    1           1           1           2           2           NULL        NULL(2 row(s) affected)
    */