db2查询组由和不同

时间:2016-10-13 11:13:24

标签: sql db2

date  shift   emp      revty
d1     s1    emp1     RL
d1     s1    emp1     RA
d1     s1    emp1     AA
d1     s1    emp1     AJ
d1     s1    emp1     RD
d1     s1    emp2     RL
d1     s1    emp2     RA
d1     s1    emp2     AA
d1     s1    emp2     AJ
d1     s1    emp2     RD
d2     s1    emp1     RL
d2     s1    emp1     RA
d2     s1    emp1     AA
d2     s1    emp1     AJ


select distinct date,shift,

对于每个不同的日期和班次,我将(RL,RA,AA,AJ,RD)或(RL,RA,AA,AJ)或(RD)。

1)所以如果特定日期和班次有(RL,RA,AA,AJ,RD)那么它的ARR-DEP为是,其他列ARR和DEP为NO(参见下面的o / p) 2)因此,如果特定日期和班次有(RL,RA,AA,AJ)那么它的ARR为是,其他列ARR-DEP和DEP为NO(参见下面的o / p) 3)所以如果特定日期和班次有(RD)那么它是DEPA是和其他列ARR-DEP和ARR为NO(参见下面的o / p)

所以我的查询结果应该是

Date  shift     ARR-DEP     ARR    DEP
d1      s1        YES       NO      NO
d1      s2         NO      YES      NO

这是我试过它不起作用的

select distinct shift,date, 
CASE WHEN REVTY in('RL','RA','RA','AJ','RD') then "ARR-DEP" 
WHEN REVTY in('RL','RA','RA','AJ') then "ARR" 
WHEN REVTY in ('RD') then "DEP" 
end
 as type
from test al group by SHIFT,DATE,type;

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select t.date, t.shift,
       (case when count(distinct case when revty in ('RL', 'RA', 'AA', 'AJ', 'RD') then revty end) = 5
             then 'YES' else 'NO'
        end) as ARR_DEP,
       (case when count(distinct case when revty in ('RL', 'RA', 'RA', 'AJ') then revty end) = 4 and
                  count(distinct revty) = 4
             then 'YES' else 'NO'
        end) as arr,
       (case when min(revty) = max(revty) and min(revty) = 'RD'
             then 'YES' else 'NO'
        end) as dep
from test t
group by t.date, t.shift;

答案 1 :(得分:0)

试试这个

select tmp.date, tmp.shift, 
case when tmp.ARR_DEP='YES' then 'YES' else 'NO' end ARR_DEP,
case when tmp.ARR_DEP='NO' and tmp.ARR='YES' then 'YES' else 'NO' end ARR,
case when tmp.ARR_DEP='NO' and tmp.ARR='NO' and tmp.DEP='YES' then 'YES' else 'NO' end DEP
from (

      select t.date, t.shift,
             (case when count(distinct case when revty in ('RL', 'RA', 'AA', 'AJ', 'RD') then revty else null end) = 5 then 'YES' else 'NO' end) as ARR_DEP,
             (case when count(distinct case when revty in ('RL', 'RA', 'RA', 'AJ') then revty else null end) = 4 then 'YES' else 'NO' end) as ARR,
             (case when count(case when revty='RD' then revty else null end)>0 then 'YES' else 'NO' end) as DEP
      from test t
      group by t.date, t.shift
) tmp