一张表里面有kh,rq日期字段,flag字段等,我现在想把日期字段拆分成两个字段,进入日期和出场日期,其中进入日期满足的条件是flag='进口机',出场日期满足的条件是flag='出口机'这个sql语句该怎么写.我用case when else语句写好像不行.请高手帮忙

解决方案 »

  1.   

    declare @tb table (kh int,rq datetime,flag varchar(20))
    insert into @tb select 1,'2008-01-01','进口机'
    insert into @tb select 1,'2008-01-02','出口机'
    insert into @tb select 2,'2008-01-03','进口机'
    insert into @tb select 2,'2008-01-04','出口机'select kh,
    max(case when flag='进口机' then rq end) as '进口日期',
    max(case when flag='出口机' then rq end) as '出口日期'
    from @tb 
    group by khkh 进口日期 出口日期
    1 2008-01-01 00:00:00.000 2008-01-02 00:00:00.000
    2 2008-01-03 00:00:00.000 2008-01-04 00:00:00.000
      

  2.   


    select kh,
    max(case flag when '进口机' then rq end) 进入日期,
    max(case flag when '出口机' then rq end) 出场日期
    from tb
    group by kh