我有2个表跟踪项目及其状态。
每个项目一次只能有1个活动状态,但该表还记录了这些项目的状态历史记录,跟踪状态发生变化的时间。
这是我现在的查询:
SELECT PROJ_NO, COMP_DATE, SPON_PROG, PROP_STATUS, AWD_S, AWD_E, AWD_AMT, DUEDT, MAX(STAT_DATE) AS STAT_DATE, ST_STATUS
FROM (
SELECT DISTINCT prsl.PROJ_NO, NVL(TO_CHAR(prsl.DEADLINE, 'YYYY-Mon-DD'), TO_CHAR(prsl.SUBMIT_DATE, 'YYYY-Mon-DD')) AS COMP_DATE,
prsl.SPON_PROG, prsl.PROP_STATUS, TO_CHAR(prsl.AWD_START, 'YYYY-Mon-DD') AS AWD_S, TO_CHAR(prsl.AWD_END, 'YYYY-Mon-DD') AS AWD_E, prsl.AWD_AMT,
TO_CHAR(dlvr.DUEDATE, 'YYYY-Mon-DD') AS DUEDT,
TO_CHAR(MAX(dlvr.ST_STAT_DATE), 'YYYY-Mon-DD') AS STAT_DATE,
dlvr.ST_STATUS
FROM adpcra.ra_v_q_ie_prsl03 prsl
LEFT JOIN adpcra.ra_v_q_ie_pt_deliver dlvr ON prsl.PROJ_NO = dlvr.PROJ_NO
WHERE prsl.EMPL_NO = '014209'
AND prsl.FIRST_PD = 1
AND (prsl.SPON_PROG LIKE 'UM-SSHRC RGP%'
OR prsl.SPON_PROG LIKE 'UM-SSHRC TGP%'
OR prsl.SPON_PROG LIKE 'URGP%'
OR prsl.SPON_PROG LIKE 'UCRP%'
OR prsl.SPON_PROG LIKE 'UIRP%'
OR prsl.SPON_PROG LIKE 'Creative Works%'
)
GROUP BY prsl.PROJ_NO, NVL(TO_CHAR(prsl.DEADLINE, 'YYYY-Mon-DD'), TO_CHAR(prsl.SUBMIT_DATE, 'YYYY-Mon-DD')),
prsl.SPON_PROG, prsl.PROP_STATUS, prsl.AWD_START, prsl.AWD_END, prsl.AWD_AMT, dlvr.DUEDATE, dlvr.ST_STATUS
)
GROUP BY PROJ_NO, COMP_DATE, SPON_PROG, PROP_STATUS, AWD_S, AWD_E, AWD_AMT, DUEDT, ST_STATUS
ORDER BY COMP_DATE DESC, STAT_DATE DESC
这是该查询的简化结果(我删除了一些列以使其更简单):
proj_no stat_date st_status
=======================================
123 2015-Feb-25 Completed
123 2015-Jan-02 Not Completed
456 2013-Aug-07 Completed
456 2012-Aug-08 Not Completed
789 2011-Jun-16 Not Completed
结果表只为我提供了我不想包含的额外行。
基本上我想要的就是获得这些:
proj_no stat_date st_status
=======================================
123 2015-Feb-25 Completed
456 2013-Aug-07 Completed
789 2011-Jun-16 Not Completed
我只想了解每个项目的最新状态。
有人可以帮帮我吗?谢谢!
它过去不是在子查询中,但我只是尝试了一些东西而最终得到了一个子查询。但结果无论哪种方式都是一样的。
答案 0 :(得分:0)
如果你已经有了这个
proj_no stat_date st_status
=======================================
123 2015-Feb-25 Completed
123 2015-Jan-02 Not Completed
456 2013-Aug-07 Completed
456 2012-Aug-08 Not Completed
789 2011-Jun-16 Not Completed
让我们称之为YourQuery
。只需使用row_number()
查找每个项目的最大日期。
SELECT proj_no, stat_date, st_status
FROM (
SELECT
Y.*,
row_number() over (partition by proj_no order by stat_date desc) as rn
FROM YourQuery Y
) T
WHERE T.rn = 1