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

时间:2009-07-28 01:16:54

标签: sql mysql formatting

之前我发布了这个,这有助于给我以下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

有人可以提供一些帮助吗?我非常感谢...

您可以在MySQL/PHP Algorithm for Weekday/Weekend count (per month)

中查看“user”和“eventcal”的模式

1 个答案:

答案 0 :(得分:2)

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)。