如何从Oracle SQL中的两个联合表中获取最大日期?

ne5o7dgx  于 2023-06-05  发布在  Oracle
关注(0)|答案(1)|浏览(261)

我目前有以下SQL,在CTE中有2个联合表。目前,MAX(DSTAMP)正在从2个联合表(2条记录)返回最大值,我想要的是两者结合时的最大日期(1条记录)。
SQL在Oracle Server中。

With TA as

(select
    SKU_ID, CODE, FROM_LOC_ID, TO_LOC_ID, EXTRA_NOTES, CONTAINER_ID,
    PALLET_ID, DSTAMP, USER_ID, UPDATE_QTY, ORIGINAL_QTY, LOCK_CODE
from  table 1
WHERE CODE = '####'
AND SITE_ID = '9999'
AND FROM_LOC_ID NOT IN ('####')

UNION

select
    SKU_ID, CODE, FROM_LOC_ID, TO_LOC_ID, EXTRA_NOTES, CONTAINER_ID, 
    PALLET_ID, DSTAMP, USER_ID, UPDATE_QTY, ORIGINAL_QTY, LOCK_CODE
from  table 2
WHERE CODE = '####'
AND SITE_ID = '9999'
AND FROM_LOC_ID NOT IN ('####')

)

SELECT
    SKU_ID, CODE, FROM_LOC_ID, TO_LOC_ID, EXTRA_NOTES, CONTAINER_ID, 
    PALLET_ID, USER_ID, UPDATE_QTY, ORIGINAL_QTY, LOCK_CODE,
    MAX(DSTAMP) as DSTAMP

FROM TA
GROUP BY
   SKU_ID, CODE, FROM_LOC_ID, TO_LOC_ID, EXTRA_NOTES, CONTAINER_ID,
   PALLET_ID, USER_ID, UPDATE_QTY, ORIGINAL_QTY, LOCK_CODE
u4dcyp6a

u4dcyp6a1#

对于一个具有max的记录,我会添加一个具有条件的having子句,例如:

HAVING MAX(DSTAMP) = (SELECT MAX(DSTAMP) FROM TA)

相关问题