带有 case 语句的 having 子句
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
table 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
感谢您的帮助
这可能就是你想要的
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'
写作sub-query作品
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';
使用 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)
我正在尝试获取具有最大日期 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
table 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
感谢您的帮助
这可能就是你想要的
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'
写作sub-query作品
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';
使用 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)