首页 > 解决方案 > 分别找出 2019 年新加入者人数最多和最少的月份

问题描述

假设我有一个employee表,其列为DateOfJoining. 我输入的数据为

2019-12-4
2019-12-6
2019-12-5
2019-10-5
2010-08-17

现在我想编写 SQL 查询来查找加入人数最多的月份。

标签: sqlsql-serverdatabasedatatable

解决方案


使用Derived tablerow_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

推荐阅读