表1中有4列,第一列l1,第2列type int,第3列flag int 第4列info  varchar
现在数据记录有如下几条:
l1     type     flag    info
1      4        0        ‘abcd’
1      4        1         ‘efgh’
2      4        0         ’higk‘
2      4        1         ’lmno‘现在想得到按l1列为分组的,记录新格式如下:
l1     type     info0     info1
1      4        ’abcd‘   ’efgh‘
2      4        ’higk‘   ’lmno‘请问该增么实现呀?小弟在这里谢谢了,实在是没有分了,请多帮忙吧。

解决方案 »

  1.   

    select l1,type,info0=case when flag=0 then info end,info1=case when flag=1 then info end
    from 表名
    group by l1,type
      

  2.   

    select * from ta t where not exists(select 1 from ta where col1=t.col1 and type=t.type and flag>t.flag)
    -------
    select * from ta t where flag=(select max(flag) from ta where col1=t.col1 and type=t.type)
    ----col1为第一列列名
      

  3.   

    select  distinct *   from   ta  where flag=1----如果flag为0或者1时
      

  4.   

    create table  tab(l1   int,        type   int,        flag  int,       info varchar(10))
    insert tab
    select 1             ,4              ,  0                 ,'abcd' 
    union select 1            ,4           ,      1                   ,'efgh'
    union select 2             ,4          ,       0                   ,'higk'
    union select 2            , 4          ,       1                   ,'lmno'--静态
    select l1,type, info0=max(case when flag=0 then info end),
    info1=max(case when flag=1 then info end)
    from tab
    group by l1,type--动态declare @s varchar(8000)
    set @s='select l1,type'select @s=@s+',info'+rtrim(flag)+'=max(case when flag='+rtrim(flag)+'then info end)'
    from tab
    group by flagset @s=@s+' from tab group by l1,type'
    exec( @s)
    drop table tab