【问题标题】:How to sperate 1 column of date to multiple columns of month in SQL?如何在 SQL 中将 1 列数据分隔为月份的多列?
【发布时间】:2022-12-05 21:00:49
【问题描述】:

我在下面有一个场景:

Name LoginDate
Peter 2020-01-01
Peter 2020-01-02
Mary 2020-01-01
Peter 2020-02-02
Mary 2020-02-05
Chris 2020-02-07

如何编写下面可以重新组织的SQL

Name Jan Feb
Peter 2 1
Mary 1 1
Chris 0 1

感谢您的帮助!

【问题讨论】:

  • 您应该指定计数是从每年还是仅从 2020 年开始。

标签: mysql


【解决方案1】:

我们可以使用Month()来做

create table login_record(
  name varchar(100),
  login_date date
);

insert into login_record(name,login_date) values
('Peter','2020-01-01'),
('Peter','2020-01-02'),
('Mary','2020-01-01'),
('Peter','2020-02-02'),
('Mary','2020-02-05'),
('Chris','2020-02-07');

SELECT
 name,
 SUM(IF(month(login_date) = 1,1,0)) AS `Jan`,
 SUM(IF(month(login_date) = 2,1,0)) AS `Feb`,
 SUM(IF(month(login_date) = 3,1,0)) AS `Mar`
 -- sum other month
FROM login_record
group by name
order by name

DB Fiddle Demo

【讨论】:

  • WOW~~非常感谢你的帮助,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多