[英]having clause with case statement
我試圖獲取具有最大日期col4_date的行分組,其中col5 = Hi。 我注意到其他人對一個案件也進行了類似的查詢。 也許我需要使用in子句來執行此操作。 最大(col4_date)就是失敗的地方。 任何建議都很好
select col1, col2, col3 from table1 t1
group by col1, col2, col3
HAVING
sum(case when ( max (col4_date) = col4_date ) and (col5 = 'Hi' ) then 1 else 0 end) > 0
表1內容
col1 | col2 | col3 | col4_date | col5 -----+------+------+-----------+----- D | F | G | 4/3/2018 | Hi D | F | G | 1/1/1970 | Bye H | I | J | 1/1/1970 | Hi H | I | J | 4/3/2018 | Bye
輸出
col1 | col2 | col3 -----+------+----- D | F | G
謝謝你的幫助
使用Oracle的KEEP LAST
獲取最后的col4_date
的col5
值:
select col1, col2, col3
from table1
group by col1, col2, col3
having max(col5) keep (dense_rank last order by col4_date) = 'Hi';
這適用於CASE以獲取結果:
select col1, col2, col3
from table1 t1
group by col1, col2, col3
HAVING -- compare overall max date and max date for 'Hi'
max(col4_date) = max(case when col5 = 'Hi' then col4_date end)
這可能是您想要的
select col1, col2, col3
from table1 t1
join (select col1, col2, col3, max(col4_date) as max_col4_date
from table1
group by col1, col2, col3
) sub on sub.col1 = t1.col1 and sub.col2 = t1.col2 and sub.col3 = t1.col3 and sub.max_col4_date = t1.col4_date
where col5 = 'Hi'
作為子查詢編寫
SELECT col1, col2, col3
FROM grp
WHERE (col1, col2, col3, col4) IN ( SELECT col1,
col2,
col3,
MAX (col4)
FROM grp
GROUP BY col1, col2, col3)
AND col5 = 'Hi';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.