sql - 分别找出 2019 年新加入者人数最多和最少的月份
问题描述
假设我有一个employee
表,其列为DateOfJoining
. 我输入的数据为
2019-12-4
2019-12-6
2019-12-5
2019-10-5
2010-08-17
现在我想编写 SQL 查询来查找加入人数最多的月份。
解决方案
使用Derived table
和row_number()
下面的查询将为您提供每年最多加入人数的月份。
select cnt,mnth,yr
from
(select count(DateOfJoining)cnt,
month(DateOfJoining)mnth,
year(DateOfJoining)yr,
row_number()over(partition by year(DateOfJoining) order by count(DateOfJoining)desc)srno
from #employee
group by month(DateOfJoining),year(DateOfJoining)
)tbl
where srno = 1
输出
cnt mnth yr
----------- ----------- -----------
1 8 2010
3 12 2019
如果您想专门针对 2019 年yr ='2019'
,请在 where 子句中添加条件。
where srno = 1
and yr =2019
输出
cnt mnth yr
----------- ----------- -----------
3 12 2019
推荐阅读
- python - 在用户定义的函数中应用函数以四舍五入
- javascript - ER_ACCESS_DENIED_NO_PASSWORD_ERROR 表示混淆
- mysql - Laravel 关系属于到哪里有
- arrays - 矩阵的滑动窗口求和
- apache-kafka - 如何在 jdbc-sink-connector 模式信息中指定数据类型“日期”?
- python - 变量中的 Python.py 文件数学
- ruby - 找不到 gem capistrano 的可执行上限
- angular - 在调用 api 之前检查 ngrx 效果中的存储数据时遇到问题
- java - Java Thymeleaf:将数据从一个表单获取到另一个表单,然后在提交时使用两者的数据
- javascript - 如何使用反应在 Ui 上显示嵌套的 json