假设我有一个employee
表,其中一列为DateOfJoining
。我输入的数据为
2019-12-4
2019-12-6
2019-12-5
2019-10-5
2010-08-17
现在,我想编写SQL查询来查找参加人数最大的月份。
答案 0 :(得分:0)
您可以在下面尝试-使用汇总和TOP
select top 1 month(dateofjoining),count(*) as totaljoining
from tablename
where year(dateofjoining)=2019
group by month(dateofjoining)
order by 2 desc
答案 1 :(得分:0)
使用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
答案 2 :(得分:0)
您既要最大又要最少-尽管我猜测您至少需要一名员工。
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
。