此查询有效,但我想看看是否有更优化/更短的方式来获得相同的结果。我想从3个表,TABLE_01,TABLE_02,TABLE_03的并集中检索具有最大日期的所有数据。无论哪个表都有最新的bill_date,我想检索该bill_date的行。它将始终为同一个PID和bill_date返回多行。
SELECT T1.PID, T1.BILL_DATE, T2.COL3, T2.COL4, T2.COL5
FROM
(
SELECT T.PID, MAX(T.BILL_DATE)
FROM
(
SELECT DISTINCT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0501
GROUP BY 1,2,3,4,5
UNION ALL
SELECT DISTINCT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0502
GROUP BY 1,2,3,4,5
UNION ALL
SELECT DISTINCT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0503
GROUP BY 1,2,3,4,5
) T
GROUP BY 1
) T1
INNER JOIN
( SELECT DISTINCT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0501
GROUP BY 1,2,3,4,5
UNION ALL
SELECT DISTINCT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0501
GROUP BY 1,2,3,4,5
UNION ALL
SELECT DISTINCT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0501
GROUP BY 1,2,3,4,5
) T2
ON T1.PID = T2.PID
AND T1.BILL_DATE = T2.BILL_DATE
答案 0 :(得分:0)
是的,QUALIFY条款在这里很方便。
SELECT * FROM
(
SELECT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0501
GROUP BY 1,2,3,4,5
UNION ALL
SELECT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0502
GROUP BY 1,2,3,4,5
UNION ALL
SELECT PID, BILL_DATE, COL3, COL4, COL5
FROM TABLE_0503
GROUP BY 1,2,3,4,5
) T
QUALIFY RANK() OVER (PARTITION BY PID ORDER BY BILL_DATE DESC) = 1;
在每组PID中,等级将分配给从BILL_DATE到最低的行。 QUALIFY ... = 1
将选择排名最高的BILL_DATE。