按月份分组

Group by Day of Month

假设我有一个 table logins,只有 bigint id,一个 datetime 类型的 date_loginfk_user 类型bigint。我需要 select 指定年份中每个月的每一天的第一次和最后一次登录。

我猜是这样的:

select *theDayOfTheMonth*,min(date_login), max(date_login)
from logins
where year(date_login) = *theYearInput* and
and fk_user = *theKeySpecified* and
month(date_login) = *theMonthInput*
group by *theDayOfTheMonth*

但我不知道如何按每月的那一天分组。我该怎么做?

你很接近。它看起来像这样:

SELECT DATE(date_login) as dayOfMonth, min(date_login), max(date_login)
FROM logins
WHERE year(date_login) = @theYearInput
    and fk_user = @theKeySpecified
    and month(date_login) = @theMonthInput
GROUP BY DATE(date_login)

或者您可以改用 the Day() function,这应该仍然有效,因为通过 WHERE 子句中的条件查询被限制在一个特定的月份:

SELECT DAY(date_login) as dayOfMonth, min(date_login), max(date_login)
FROM logins
WHERE year(date_login) = @theYearInput
    and fk_user = @theKeySpecified
    and month(date_login) = @theMonthInput
GROUP BY DAY(date_login)

在功能上,给定这些条件,它们之间的唯一区别是输出中第一列的格式。但是,如果您以后需要扩展到更大的日期范围,第一个版本会处理得更好。

您要查找的函数是DayOfMonth()

create table logins(
fk_user bigint,
date_login datetime);
insert into logins values
(1,'2022-01-01 09:00:00'),(1,'2022-01-01 18:00:00'),(1,'2022-01-02 08:00:00'),(1,'2022-01-02 16:00:00')
select 
  DayOfMonth(date_login) day,
  min(date_login) first_login, 
  max(date_login) last_login
from logins
where year(date_login) = 2022 
and fk_user = 1 and
month(date_login) = 1
group by DayOfMonth(date_login);
day | first_login         | last_login         
--: | :------------------ | :------------------
  1 | 2022-01-01 09:00:00 | 2022-01-01 18:00:00
  2 | 2022-01-02 08:00:00 | 2022-01-02 16:00:00

db<>fiddle here