【发布时间】:2019-04-26 05:19:26
【问题描述】:
假设我有一个employee 表,其列为DateOfJoining。我已将数据输入为
2019-12-4
2019-12-6
2019-12-5
2019-10-5
2010-08-17
现在我想编写 SQL 查询来查找加入人数最多的月份。
【问题讨论】:
-
是什么阻止你编写 sql 查询?
标签: sql sql-server database datatable
假设我有一个employee 表,其列为DateOfJoining。我已将数据输入为
2019-12-4
2019-12-6
2019-12-5
2019-10-5
2010-08-17
现在我想编写 SQL 查询来查找加入人数最多的月份。
【问题讨论】:
标签: sql sql-server database datatable
您可以在下面尝试 - 使用聚合和 TOP
select top 1 month(dateofjoining),count(*) as totaljoining
from tablename
where year(dateofjoining)=2019
group by month(dateofjoining)
order by 2 desc
【讨论】:
使用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 年,请在 where 子句中添加条件 yr ='2019'。
where srno = 1
and yr =2019
输出
cnt mnth yr
----------- ----------- -----------
3 12 2019
【讨论】:
你想要最大的和最少的——尽管我猜你想要至少一名员工。
with e as (
select year(dateofjoining) as yyyy,
month(dateofjoining) as mm,
count(*) as totaljoining
from employee
where dateofjoining >= '2019-01-01' and
dateofjoining < '2020-01-01'
group by year(dateofjoining), month(dateofjoining)
)
select e.*
from ((select top (1) e.*
from e
order by totaljoining asc
) union all
(select top (1) e.*
from e
order by totaljoining desc
)
) e;
注意事项:
group by 仅表示一次。top (1) with ties。【讨论】: