我一张表只有id和name字段,大概有个100条数据
我感觉select * from tab1  这样每行显示2列显示的结果太长了,要100行
我想要的查询结果拆成4列(id1,name1,id2,name2),结果变成50行数据 ,怎么写这个sql?

解决方案 »

  1.   

    id是连续的话  我自己也会写
    tab1 a left join tab1 b on b.id=a.id+1 where a.id%2=1
      

  2.   

    既然会写
    那就创造ID连续
    思路都一样的
    根据连续的ID判断
    分两列
      

  3.   

    set nocount on
    declare @i int
    set @i=1
    declare @t table(ID int,[name] varchar(10))
    while @i<=100
      begin
        insert @t select @i,char(64+@i)+'test'
        set @i=@i+1
      end
    select 
           max(case when (ID-1)%2=0 then ID else null end)[ID1],
           max(case when (ID-1)%2=0 then name else null end)[Name1],
           max(case when (ID-1)%2=1 then ID else null end)[ID2],
           max(case when (ID-1)%2=1 then name else null end)[Name2]
    from @t
    group by (ID-1)/2
    /*
    ID1         Name1      ID2         Name2
    ----------- ---------- ----------- ----------
    1           Atest      2           Btest
    3           Ctest      4           Dtest
    5           Etest      6           Ftest
    7           Gtest      8           Htest
    9           Itest      10          Jtest
    11          Ktest      12          Ltest
    ..................
    */
      

  4.   

    2000可以通过子查询实现ID连续 然后嵌套查询 
    或者通过临时表
    2005 可以通过row_number实现ID连续