我想根据最新的“ APP_START_DT”返回每人1行。
我想确保它查看MAX(APP_START_DT),然后跟踪该人在该行上的所有日期,而忽略该行上的其他行和日期。
This is what I have tried:
select distinct ap1.ID,
MAX(ap1.APP_START_DT) over (PARTITION by ap1.ID) APP_START_DT,
ap1.APP_SUBMIT_DT
from table1 ap1
where ap1.ID in ('444','555');
Getting 2 rows for both of these ids.
My Table:
ID NAME Acct_CR_DT App_Ap APP_START_DT APP_SUBMIT_DT
444 ABC1 9/5/2018 My univ 9/5/2018 9/14/2018
444 ABC1 9/5/2018 {null} {null} {null}
555 ABC2 1/9/2019 {null} {null} {null}
555 ABC2 1/9/2019 Univ4 1/9/2019 1/9/2019
Desired Results:
ID NAME Acct_CR_DT App_Ap APP_START_DT APP_SUBMIT_DT App_stat
444 ABC1 9/5/2018 My univ 9/5/2018 9/14/2018 Submt
555 ABC2 1/9/2019 Univ4 1/9/2019 1/9/2019 Submt
答案 0 :(得分:0)
按ap1.ID分组可以让您在获得MAX APP_START_DT的同时,每个ID获得一行
SELECT distinct ap1.ID, MAX(ap1.APP_START_DT)
FROM table1 ap1
WHERE ap1.ID in ('444','555')
GROUP BY ap1.ID ;
答案 1 :(得分:0)
您可以应用null处理功能以获得所需的结果。
select distinct ap1.ID,
MAX(ap1.APP_START_DT) over (PARTITION by ap1.ID) APP_START_DT,
ap1.APP_SUBMIT_DT
from (select COALESCE(APP_START_DT, 'lowest_date') as APP_START_DT, ID, APP_SUBMIT_ID from table1 where ID in ('444','555')) ap1;
答案 2 :(得分:0)
关于FIRST_VALUE / LAST_VALUE(以及根据用户ID划分窗口?):
SELECT DISTINCT
ID, NAME,
LAST_VALUE(Acct_CR_DT) OVER(PARTITION BY ID ORDER BY APP_START_DT NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),
LAST_VALUE(App_Ap) OVER(PARTITION BY ID ORDER BY APP_START_DT NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),
LAST_VALUE(APP_START_DT) OVER(PARTITION BY ID ORDER BY APP_START_DT NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),
LAST_VALUE(APP_SUBMIT_DT) OVER(PARTITION BY ID ORDER BY APP_START_DT NULLS FIRST RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM table1 ap1
对于每一行,我们为每个用户ID /名称对找到每一列的“最后一个值”。我们需要DISTINCT来删除重复项,因为此“最后一个值”是为每一行(不仅是每个组中的最后一个)计算的。
如果可行,如果可以保证,将只有APP_START_DT = MAX(APP_START_DT)OVER(PARTITION BY ID)的行,或者如果存在更多此类行,则它们至少与所选列保持一致。如果您不能保证,我会考虑在ORDER BY子句中添加更多列(该行实际上应该是第一行)。
答案 3 :(得分:0)
select *
FROM table1
where (id, app_start_dt) IN (
SELECT ap1.ID, MAX(ap1.APP_START_DT)
FROM table1 ap1
WHERE ap1.ID in ('444','555')
GROUP BY ap1.ID
) ;
哈维尔很近。如果您使用他的查询作为子选择,我相信它会起作用。很高兴知道数据是什么样子,以及在任何给定日期是否存在重复项,因为这样做会破坏这种方法。
答案 4 :(得分:0)
SELECT *
FROM
(
SELECT *
FROM mytable
WHERE id IN(444, 555)
) T1
INNER JOIN
(
SELECT id,
MAX(APP_START_DT) APP_START_DT
FROM mytable
WHERE id IN(444, 555)
GROUP BY ID
) T2 ON T1.id = T2.ID
AND T1.APP_START_DT = T2.APP_START_DT;