gpt4 book ai didi

sql - 如何从基于多个表的 Oracle 结果集中删除重复项

转载 作者:行者123 更新时间:2023-12-02 00:27:45 26 4
gpt4 key购买 nike

我有 2 个表:一个保存核心数据的主 APPLICATION 表,以及一个反射(reflect) APPLICATION 表中核心数据状态变化的 STATUSTRACKING 表。

APPLICATION表和STATUSTRACKING表之间是1:N的关系。示例如下:

-- APPLICATION
SELECT A.ID, A.DECISIONON, A.APPLICATIONSTATUS_ID AS CURRENTSTATUS
FROM APPLICATION A
WHERE A.ID=1099;

Results:
ID DECISIONON CURRENTSTATUS
1099 5/05/2009 5

-- STATUS TRACKING
SELECT ST.ID, ST.APPLICATION_ID AS APP_ID, ST.APPLICATIONSTATUS_ID AS STATUS, ST.CREATEDATE
FROM STATUSTRACKING ST
WHERE ST.APPLICATION_ID=1099
ORDER BY ST.CREATEDATE DESC;

Results:
ID APP_ID STATUS CREATEDATE
44466 1099 5 5/05/2009
44458 1099 7 5/05/2009
10826 1099 8 21/07/2008
9770 1099 7 9/07/2008
4410 1099 3 9/05/2008
3814 1099 2 2/05/2008
3803 1099 1 2/05/2008

问题:我需要为特定状态选择具有最近日期的 STATUSTRACKING 记录。这是我的尝试:

SELECT A.ID AS APP_ID, A.APPLICATIONSTATUS_ID AS CURR_ST, Z.ID AS ST_ID, Z.CREATEDATE, Z.APPLICATIONSTATUS_ID AS OLD_ST
FROM APPLICATION A, STATUSTRACKING Z
WHERE A.APPLICATIONSTATUS_ID in (5,6)
AND A.ID IN (337,1099,1404,9441)
AND Z.APPLICATIONSTATUS_ID = 7
AND Z.APPLICATION_ID=A.ID
ORDER BY A.ID ASC, Z.CREATEDATE DESC;

Results:
APP_ID CURR_ST ST_ID CREATEDATE OLD_ST
337 6 13978 17/08/2008 7
1099 5 44458 5/05/2009 7
1099 5 9770 9/07/2008 7
1404 6 15550 28/08/2008 7
9441 5 49271 3/06/2009 7
9441 5 46058 13/05/2009 7

问题是重复的行。我必须只显示具有最新 CreateDate 的行。在 App_ID 1099 的情况下,它将是这条记录:

1099    5       44458       5/05/2009   7

我显然不想排除不重复的行。

我认为我在这条语句的正确轨道上给出了我正在寻找的行:

SELECT A.ID, A.APPLICATION_ID, A.APPLICATIONSTATUS_ID, A.CREATEDATE
FROM (SELECT *
FROM STATUSTRACKING
WHERE APPLICATIONSTATUS_ID=7
AND APPLICATION_ID=1099
ORDER BY CREATEDATE DESC) A
WHERE ROWNUM = 1;

...但我似乎无法让它与我的主要选择语句一起使用。

我想要的结果集应该是这样的:

APP_ID  CURR_ST ST_ID       CREATEDATE  OLD_ST
337 6 13978 17/08/2008 7
1099 5 44458 5/05/2009 7
1404 6 15550 28/08/2008 7
9441 5 49271 3/06/2009 7
etc. ...

我不是 Oracle/SQL 专家,因此我们将不胜感激。

最佳答案

最简单的方法可能是使用解析函数。有点像

SELECT *
FROM (
SELECT A.ID AS APP_ID,
A.APPLICATIONSTATUS_ID AS CURR_ST,
Z.ID AS ST_ID,
Z.CREATEDATE,
Z.APPLICATIONSTATUS_ID AS OLD_ST,
rank() over (partition by a.id order by z.createDate desc) rnk
FROM APPLICATION A,
STATUSTRACKING Z
WHERE A.APPLICATIONSTATUS_ID in (5,6)
AND A.ID IN (337,1099,1404,9441)
AND Z.APPLICATIONSTATUS_ID = 7
AND Z.APPLICATION_ID=A.ID
)
WHERE rnk = 1

如果可能有关系,您可能希望使用 ROW_NUMBERDENSE_RANK 分析函数而不是 RANK

关于sql - 如何从基于多个表的 Oracle 结果集中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8221644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com