id class time flag
1 101 1000 1
1 101 2000 2
2 101 3000 2
10 101 4000 1
...
...
...
这是一个表
我要查询出如下的数据
id class time1 time2
1 101 1000 2000
2 101 0 3000
10 101 4000 0
...
...
...
time1就是flag=1时候的time
time2就是flag=2时候的time
像id=2的时候,他只有flag=2的time,
而id=10的时候,他只有flag=1的time
我好难查询,要考虑到效率的问题,求高手帮忙

解决方案 »

  1.   

     select id, 
     max(case when [flag] ='1' then time else '' end) as test1,
     max(case when [flag] ='2'  then time else '' end )as test2
     from  [TB]
     group by id
      

  2.   


    --> 数据库版本:
    --> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
    --> 测试数据:[TB]
    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TB]') 
    AND type in (N'U')) --U 代表你查询的是表
    DROP TABLE [TB]
    GO---->建表
    create table [TB]([id] int,[class] int,[time] int,[flag] int)
    insert [TB]
    select 1,101,1000,1 union all
    select 1,101,2000,2 union all
    select 2,101,3000,2 union all
    select 10,101,4000,1
    GO--> 查询结果
      select id, class, 
     max(case when [flag] ='1' then time else '' end) as test1,
     max(case when [flag] ='2'  then time else '' end )as test2
     from  [TB]
     group by id,class 
      

  3.   


    select id,class,max((case when flag=1 then time else 0 end)) as time1,
               max((case when flag=2 then time else 0 end)) as time2
     from tb group by id,class
      

  4.   


    select id,class,sum(time1) as time1,sum(time2) as time2
    from
    (
    select id,class,sum(case when flag=1 then time else 0 end) as time1
    ,sum(case when flag=2 then time else 0 end )as time2
    from tb
    ) a 
    group by a.id,class
      

  5.   


    select id,class,sum(case when flag=1 then time else 0 end) as time1
    ,sum(case when flag=2 then time else 0 end )as time2
    from tb
    group by id,class
      

  6.   

    犀利
    case when [flag] ='1' then time else '' end。。