如何从多个表 Oracle 中获取最后两个最大日期

Posted

技术标签:

【中文标题】如何从多个表 Oracle 中获取最后两个最大日期【英文标题】:How to take last two maximum dates from multiple tables Oracle 【发布时间】:2018-12-27 00:43:32 【问题描述】:

我有 4 张桌子,我正在尝试从这 4 张桌子中获取最后两个最大日期。我在下面列出了我的查询:

WITH LAST_ATT_DATE AS 
        (
        SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
        FROM TABLE1
        WHERE NUM_REF='E1'
        UNION
        SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
        FROM TABLE2
        WHERE NUM_REF='E1'
        UNION
        SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
        FROM TABLE3
        WHERE NUMREF='E1'
        UNION
        SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
        FROM TABLE4
        WHERE NUMREF='E1'
        )

        SELECT MAX(decode(RANK,1,LAST_DATE)),MAX(decode(RANK,2,LAST_DATE)) 
        FROM (SELECT NUMBER1,LAST_DATE,Row_Number() OVER(PARTITION BY NUMBER1 
        ORDER BY LAST_DATE DESC) AS RANK 
        FROM LAST_ATT_DATE) WHERE RANK <= 2
        GROUP BY NUMBER1 ORDER BY NUMBER1;

对于某些记录,它工作正常,对于许多记录,它显示相同的日期(仅第一个最大日期),即使它有第二个最大日期。

请有人更正此代码或建议任何其他替代方法。

【问题讨论】:

【参考方案1】:

希望,我正确理解了这个问题。请检查以下查询。

    WITH LAST_ATT_DATE AS 
    (
    SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
    FROM TABLE1
    WHERE NUM_REF='E1'
    UNION
    SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
    FROM TABLE2
    WHERE NUM_REF='E1'
    UNION
    SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
    FROM TABLE3
    WHERE NUMREF='E1'
    UNION
    SELECT NUMREF AS NUMBER1,DATE AS LAST_DATE
    FROM TABLE4
    WHERE NUMREF='E1'
    )

    SELECT NUMBER1 , MAX(CASE WHEN RN=1 THEN LAST_DATE END) LAST_DATE_1,
    MAX(CASE WHEN RN=2 THEN LAST_DATE END) LAST_DATE_2
    FROM (SELECT NUMBER1,LAST_DATE,Row_Number() OVER( 
    ORDER BY LAST_DATE DESC) AS RN 
    FROM LAST_ATT_DATE) WHERE RN <= 2
    GROUP BY NUMBER1 ORDER BY NUMBER1;

【讨论】:

【参考方案2】:

您需要使用dense_rank() 而不是row_number()

SELECT NUMBER1,
       MAX(CASE WHEN seqnum = 1 THEN LAST_DATE END),
       MAX(CASE WHEN seqnum = 2 THEN LAST_DATE) 
FROM (SELECT NUMBER1, LAST_DATE,
             DENSE_RANK() OVER (PARTITION BY NUMBER1 
                                ORDER BY LAST_DATE DESC
                               ) AS seqnum 
      FROM LAST_ATT_DATE
     ) lad
     WHERE seqnum <= 2
GROUP BY NUMBER1
ORDER BY NUMBER1;

【讨论】:

【参考方案3】:

感谢大家的回复。

我的问题得到了解决方案。我只是截断了日期列并尝试了它的工作。

选择 NUMREF 作为 NUMBER1,trunc(DATE) 作为 LAST_DATE 来自表 1,其中 NUMREF='E1';

再次感谢大家。

【讨论】:

以上是关于如何从多个表 Oracle 中获取最后两个最大日期的主要内容,如果未能解决你的问题,请参考以下文章

从多个表返回最大日期加入oracle

SQL从日期范围内的同一表中的不同记录中获取多个项目的总和(ORACLE)

如何检索表的值以获取sql中两列的最大值

如何从两个表中获取公共项目 - Oracle

用php在mysql中,如何截取最大日期和最小日期

从查找表中获取每个类型和每个日期的最大 ID