我有一个表格,格式如下:
ID,FLAG,PERIOD
4,"C",7/19/2017
4,"C",7/22/2017
4,"R",7/22/2017
4,"R",7/26/2017
数据:
with temp as (
select 4 as ID, 'R' as Flag, to_date('07/26/2017', 'mm/dd/yyyy') as Period from dual union
select 4 as ID, 'R' as Flag, to_date('07/22/2017', 'mm/dd/yyyy') as Period from dual union
select 4 as ID, 'C' as Flag, to_date('07/22/2017', 'mm/dd/yyyy') as Period from dual union
select 4 as ID, 'C' as Flag, to_date('07/19/2017', 'mm/dd/yyyy') as Period from dual)
我希望得到一个表示ID
的结果,以及此max(Period)
标志为“C”的ID
是否大于相应的max(Period)
标志为“R”的地方。
我想要的结果是(因为C的最大(期间)是22/7/2017,R的最大(期间)是26/07/2017:
ID IS_GREATER
4 NO
我考虑过使用ID和Flag以及max(Period)进行查询,然后再做一个case语句。由于我是新手,我想知道有更好的方法吗?
答案 0 :(得分:1)
with temp
as (select 4 as ID, 'R' as Flag, to_date('07/26/2017', 'mm/dd/yyyy') as Period from dual
union
select 4 as ID, 'R' as Flag, to_date('07/22/2017', 'mm/dd/yyyy') as Period from dual
union
select 4 as ID, 'C' as Flag, to_date('07/22/2017', 'mm/dd/yyyy') as Period from dual
union
select 4 as ID, 'C' as Flag, to_date('07/19/2017', 'mm/dd/yyyy') as Period from dual
union
select 5 as ID, 'R' as Flag, to_date('07/26/2016', 'mm/dd/yyyy') as Period from dual
union
select 5 as ID, 'R' as Flag, to_date('07/22/2016', 'mm/dd/yyyy') as Period from dual
union
select 5 as ID, 'C' as Flag, to_date('07/22/2017', 'mm/dd/yyyy') as Period from dual
union
select 5 as ID, 'C' as Flag, to_date('07/19/2017', 'mm/dd/yyyy') as Period from dual)
select ID
, case
when max(case when FLAG = 'C' then Period else null end) > max(case when FLAG = 'R' then Period else null end) then
'Y'
else
'N'
end
is_greater
from temp
group by ID;