有案例陈述的条款

时间:2018-04-03 18:41:42

标签: sql oracle having

我正在尝试获取具有最大日期col4_date的行分组,其中col5 = Hi。我注意到其他人对案例进行了类似的查询。也许我需要使用in子句来执行此操作。 max(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   

感谢您的帮助

4 个答案:

答案 0 :(得分:1)

使用Oracle的KEEP LAST获取上一个col5的{​​{1}}值:

col4_date

答案 1 :(得分:1)

这会使用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)

答案 2 :(得分:0)

这可能是你想要的

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'

答案 3 :(得分:0)

作为子查询编写

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';