【问题标题】:Find the months in 2019 that had the highest and least number of new joinees respectively分别找出 2019 年新加入者人数最多和最少的月份
【发布时间】: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


【解决方案1】:

您可以在下面尝试 - 使用聚合和 TOP

select top 1 month(dateofjoining),count(*) as totaljoining
from tablename
where year(dateofjoining)=2019
group by month(dateofjoining)
order by 2 desc

【讨论】:

  • 如果我想找到 2019 年最大连接度的月份怎么办。
  • 我已经编辑了 - 只是需要一个 where 条件 @Pankaj4U
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你想要最大的和最少的——尽管我猜你想要至少一名员工。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 2019-12-19
      • 2020-06-07
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多