Oracle join以获取最大数据和非分组列

时间:2016-11-10 16:48:58

标签: oracle

考虑我的查询的这一部分:

SELECT field1, field2, field3, ...

LEFT JOIN (
    SELECT field1, field2, MAX(field3) field3
    FROM table
    WHERE field2 IN ('1','2','3','4')
    AND field4 > SYSDATE - 365
    GROUP BY field1, field2) jointable ON other.fk= jointable.field1

所以field4是一个约会。我需要table的日期。如果我将其添加到选择列表中,我必须将其添加到组中,因此它将不再以拉MAX(field3)的方式进行分组。

我可以在主键上再次加入table,但这似乎并不理想。有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

您可以使用the aggregate keep dense_rank sytnax获取与每个field3组合的最大field1/2值相关联的日期:

SELECT field1, field2, field3, ...

LEFT JOIN (
    SELECT field1, field2, MAX(field3) field3,
        MAX(field4) KEEP (DENSE_RANK LAST ORDER BY field3) field4
    FROM table
    WHERE field2 IN ('1','2','3','4')
    AND field4 > SYSDATE - 365
    GROUP BY field1, field2) jointable ON other.fk= jointable.field1

仅对子查询进行快速演示,其中包含一些简单数据的CTE,其中最高field3不在最新的field4日期:

with your_table (field1, field2, field3, field4) as (
  select 'A', '1', 1, date '2016-11-01' from dual
  union all select 'A', '1', 2, date '2016-09-30' from dual
)
SELECT field1, field2, MAX(field3) field3,
  MAX(field4) KEEP (DENSE_RANK LAST ORDER BY field3) field4
FROM your_table
WHERE field2 IN ('1','2','3','4')
AND field4 > SYSDATE - 365
GROUP BY field1, field2
/

F F     FIELD3 FIELD4    
- - ---------- ----------
A 1          2 2016-09-30

答案 1 :(得分:0)

似乎窗口功能在这里运作良好......

SELECT field1, field2, field3, ...

LEFT JOIN (
    SELECT field1, field2, MAX(field3) over (partition by field1, field2) field3, Field4
    FROM table
    WHERE field2 IN ('1','2','3','4')
    AND field4 > SYSDATE - 365
    GROUP BY field1, field2, field4) jointable ON other.fk= jointable.field1

字段3的最大值现在将独立于字段4,但仍依赖于字段1和2.