首页 > 解决方案 > Sql - 从 oracle sql 中的结果集中获取最大值

问题描述

我正在尝试从结果集中获取产品的最大值,但我只得到一行值。我想显示结果集中每个产品的最大值。

请找到结果集:

|Col1     |col2        |col3|    col4 |sum_cnt|
+---------+------------+---------+----------+-------+
|     1003|     2018/03| PC |    Prod1| 105984| 
|     1003|     2018/03| PC |    Prod2|      3| 
|     1003|     2018/03| PC |    Prod3|    695| 
|     1003|     2018/03| PC |    Prod4|   8489| 
|     1003|     2018/02| PC |    Prod1| 101894| 
|     1003|     2018/02| PC |    Prod4|   7758| 
|     1003|     2018/02| PC |    Prod3|    780| 
|     1003|     2018/02| PC |    Prod2|      1| 
|     1003|     2018/01| PC |    Prod4|   7665| 
|     1003|     2018/01| PC |    Prod3|    708| 
|     1003|     2018/01| PC |    Prod2|      5| 
|     1003|     2018/01| PC |    Prod1| 104557| 
|     1003|     2017/12| PC |    Prod2|      2| 
|     1003|     2017/12| PC |    Prod1| 106896| 
|     1003|     2017/12| PC |    Prod3|    857| 
|     1003|     2017/12| PC |    Prod4|   8177| 
|     1003|     2017/11| PC |    Prod2|      1| 
|     1003|     2017/11| PC |    Prod1| 102664| 
|     1003|     2017/11| PC |    Prod3|    724| 
|     1003|     2017/11| PC |    Prod4|   7661| 
+---------+------------+---------+----------+-------+

我想为每个产品显示最新日期的 Max sum_cnt。

我希望我的输出为:

|Col1     |col2        |col3|    col4 |sum_cnt|
+---------+------------+---------+----------+-------+
|     1003|     2018/03| PC |    Prod1| 106896| 
|     1003|     2018/03| PC |    Prod2|      5| 
|     1003|     2018/03| PC |    Prod3|    857| 
|     1003|     2018/03| PC |    Prod4|   8489| 

我已尝试以下查询来获取数据,但我只得到一条记录。

这是代码:

select * from tab2 a where sum_cnt = (select max(sum_cnt)  from tab2 b where a.col1= b.col1)

请帮助我如何实现这一目标。

非常感谢您的帮助。

标签: sqloracleoracle11g

解决方案


我们可以ROW_NUMBER在这里尝试使用:

SELECT Col1, col2, col3, col4, sum_cnt
FROM
(
    SELECT t.*,
        ROW_NUMBER() OVER (PARTITION BY col1, col4 ORDER BY col2 DESC, sum_cnt DESC) rn
    FROM yourTable t
) t
WHERE rn = 1;

这里的逻辑是按产品分区,然后按第一个日期降序排序,得到最近的日期,然后按计数降序,得到最近日期的最高计数。


推荐阅读