【问题标题】:How to select records with maximum values in two columns?如何选择两列中具有最大值的记录?
【发布时间】:2013-11-14 15:08:43
【问题描述】:

很难为这个问题想出一个可以理解的标题。 我会尝试用一个例子来解释。

首先我在 Oracle DB 中有一个简单的表 INFO

year      type      message
----      ----      -------
2001      1         cakes are yammy
2003      2         apples are dangerous
2012      2         bananas are suspicious
2005      3         cats are tricky

我需要选择某些类型的最新消息(例如type = 1type = 2):

2001      1         cakes are yammy
2012      2         bananas are suspicious

所以我使用了查询:

select * from INFO i 
where year = (select max(year) from INFO i_last where i.type = i_last.type) 
and i.type in (1, 2)

但现在我需要在我的 INFO 表中添加一个新的“季度”列。并按年份和季度选择最新的记录。

year      quarter      type      message
----      -------      ----      -------
2001      2            1         cakes are yammy
2012      3            2         onions are cruel
2012      1            2         bananas are suspicious
2005      1            3         cats are tricky

类型 1 或 2 的最新记录将是:

2001      2            1         cakes are yammy
2012      3            2         onions are cruel

这样的查询应该是什么样子?

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    分析函数是你的朋友:

    SELECT   MAX( year    ) KEEP ( DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC ) AS year,
             MAX( quarter ) KEEP ( DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC ) AS quarter,
             MAX( message ) KEEP ( DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC ) AS message,
             type
    FROM     info
    GROUP BY type;
    

    SQLFIDDLE

    【讨论】:

    • 在 MS Access 中是否有等价物?你的答案是为人们打开一个全新的世界。
    【解决方案2】:

    试一试:

    SELECT i.year, i.quarter, i.type, i.message
    FROM INFO i
    JOIN INFO iy
        ON i.type = iy.type
    JOIN INFO iq
        ON iq.type = iy.type    
    WHERE i.type IN (1,2)   
    GROUP BY i.year, i.quarter, i.type, i.message   
    HAVING i.year = MAX(iy.year) AND i.quarter = MAX(iq.quarter)
    

    【讨论】:

    • 这个位阻止我获得独特的结果:“AND i.quarter = MAX(iq.quarter)” - 有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多