一尘不染

MySQL工作日/周末计数-第二部分

sql

我以前曾发布过有关此内容的文章,这有助于我获得以下SQL:

 SELECT fname, MONTH( eventDate ) , IF( WEEKDAY( eventDate ) <5, 'weekday', 'weekend' ) AS
 DAY , COUNT( * )
 FROM eventcal AS e
 LEFT JOIN users AS u ON e.primary = u.username
 GROUP BY fname, MONTH( eventDate ) , IF( WEEKDAY( eventDate ) <5, 'weekday', 'weekend' ) ;

这给了我以下结果:

 fname  MONTH( eventDate )  DAY     COUNT( * )
 Kevin  7                   weekday     3
 Kevin  7                   weekend     1
 Missy  7                   weekday     3
 Missy  7                   weekend     1

我在尝试实现以下格式时遇到了一些麻烦:

 fname  MONTH( eventDate )  Weekday COUNT     WEEKEND COUNT
 Kevin   7                   3                  1
 Missy     7                   3                  1

任何人都可以提供帮助吗?我将不胜感激…


阅读 124

收藏
2021-05-16

共1个答案

一尘不染

SELECT
fname,
MONTH(eventDate),
SUM(IF(WEEKDAY(eventDate) < 5,1,0)) AS WeekdayCount,
SUM(IF(WEEKDAY(eventDate) >= 5,1,0)) AS WeekendCount
FROM eventcal AS e
LEFT JOIN users AS u ON e.primary = u.username
GROUP BY fname, MONTH(eventDate);

您要在SELECT中进行汇总(在这种情况下为SUM),然后按希望的方式按GROUP BY汇总(按fname,按MONTH)。

2021-05-16