sql - 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)
请帮助我如何实现这一目标。
非常感谢您的帮助。
解决方案
我们可以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;
这里的逻辑是按产品分区,然后按第一个日期降序排序,得到最近的日期,然后按计数降序,得到最近日期的最高计数。
推荐阅读
- javascript - 根据事件时间将日历事件添加到自定义日历 - Angular 6
- string - KDB:如何将日期时间转换为格式化字符串?
- solr - Solr edismax 不使用逻辑运算符 AND/OR
- go - 有人可以解释这个使用通道的 Go 代码块吗?我不明白它是如何一次执行 500 个操作的
- javascript - 获取带有 base64 图像的页面
- git - Git问题推送
- algorithm - 有向无环图可以有零边吗?
- python - 如何检测视频中是否有闪光灯(或光源)?
- android - 使用相机源无法打开手电筒
- r - 在R中的另一个表中创建一个以值为条件的二进制变量