[英]db2 query group by and distinct
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为否(请参阅o / p)3)如果特定日期和班次具有(RD)那么它是DEPas是,其他列ARR-DEP和ARR为否(请参阅下面的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;
您可以使用条件聚合:
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;
尝试这个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.