查找2019年分别有最高和最低新加入人数的月份

时间:2019-04-26 05:19:26

标签: sql sql-server database datatable

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

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

现在,我想编写SQL查询来查找参加人数最大的月份。

3 个答案:

答案 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 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年使用,则在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;

注意:

  • 日期比较使用对日期的直接比较,而不是使用函数。这是最佳做法,因此优化程序可以使用索引。
  • 您既要获得最小值,又要获得最大值,因此使用CTE,因此group by仅代表一次。
  • 如果没有员工,这将不会返回几个月。
  • 如果要联系,请使用top (1) with ties