sql - 按日期计算前 5 个值
问题描述
我有一个表defect_description
和productionday
字段如下:
+--------------------+---------------+
| defect_description | productionday |
+--------------------+---------------+
| BLOWN GASKET | 2020-01-01 |
| BLOWN GASKET | 2020-01-01 |
| BLOWN GASKET | 2020-01-01 |
| BLOWN TIRE | 2020-01-01 |
| BLOWN LIGHT | 2020-01-01 |
| BLOWN LIGHT | 2020-01-01 |
| BLOWN LIGHT | 2020-01-01 |
| BLOWN LIGHT | 2020-01-01 |
| BLOWN TIRE | 2020-02-01 |
| BLOWN TIRE | 2020-02-01 |
| BLOWN TIRE | 2020-02-01 |
+--------------------+---------------+
我如何计算每天的前 5 个缺陷:
+---------------+--------------------+-------+
| productionday | defect_description | count |
+---------------+--------------------+-------+
| 2020-01-01 | BLOWN LIGHT | 4 |
| 2020-01-01 | BLOWN GASKET | 3 |
| 2020-01-01 | BLOWN TIRE | 1 |
| 2020-02-01 | BLOWN TIRE | 3 |
+---------------+--------------------+-------+
解决方案
我认为这可以满足您的要求:
select t.*
from (select defect_description, productionday, count(*) as c,
row_number() over (partition by productionday order by count(*) desc) as seqnum
from tab
group by productionday, defect_description
) t
where seqnum <= 5
推荐阅读
- wordpress - sprintf 与 __() 翻译和 javascript
- java - 需要帮助解释这个素数程序是如何工作的
- java - 如何将助焊剂链接到另一个助焊剂/单声道并施加另一个背压?
- java - 偶数索引为正数,奇数索引为负数的程序
- python - gTTS(谷歌文本到语音)模块的python代码错误
- java - Android:无法发出位置请求对话框并在回调时获取位置
- python - python3中的迷宫
- python - 使用范围作为字典中的键值,最有效的方式?
- java - 为什么这段代码会抛出 ClassCastException?
- c++11 - 减法在宏定义中如何工作