1

我有以下查询,它显示了一周中每一天的计费小时数

SELECT DAYNAME(record_date),
      sum(value)
FROM acx_time_records
WHERE
  acx_time_records.state = 3
  AND record_date >= '2012-10-1' AND record_date <= '2012-10-7'    
  AND user_id = 7 
  GROUP BY
  dayname(acx_time_records.record_date)
  ORDER BY weekday(acx_time_records.record_date)

上述查询输出以下结果:

Tuesday    9.75
Friday     1

我遇到的问题是我需要将值绘制到一个图表中,该图表已经将 X 轴定义为一周中的每一天:

 Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

因此,我需要传递一周中的每一天以获得结果,而不仅仅是结果中显示的特定天/小时。我考虑过加入一个新表,该表具有一周中的每个日历日和一天索引,但我不确定这怎么可能。理想的输出是:

Monday    0
Tuesday   9.75
Wednesday 0
Thursday  0
Friday    1
Saturday  0
Sunday    0

任何有关我如何完成此任务的提示/建议将不胜感激。我知道这也可以通过将 MySQL 与 PHP 结合来促进,但我正在尝试以一种尽可能只需要 MySQL 的方式来做到这一点。

4

2 回答 2

2

LEFT JOIN 的解决方案。

您可以按照 newfurniturey 的建议使用附加表或使用一些带有 UNION 的 SELECT。我还在连接表中找到了 WHERE 过滤器。

CREATE TABLE week_days(
  week_day_num INT(11) DEFAULT NULL
);

INSERT INTO week_days(week_day_num) VALUES (1),(2),(3),(4),(5),(6),(7);

SELECT
  DAYNAME(atrrecord_date),
  SUM(atr.value),
  COALESCE(SUM(atr.value) , 0)
FROM week_days wd
  LEFT JOIN (
      SELECT * FROM acx_time_records
      WHERE
        acx_time_records.state = 3
        AND record_date >= '2012-10-1' AND record_date <= '2012-10-7'    
        AND user_id = 7 
    ) atr
    ON wd.week_day_num = DAYOFWEEK(atr.record_date)
GROUP BY
  DAYOFWEEK(atr.record_date);
于 2012-10-09T05:27:54.423 回答
1

实际上,我建议您按照最初的想法加入另一个表,但是您可以将其设置为带有LEFT JOIN子句的简单别名表:

SELECT
    days.day,
    IF (value IS NULL, 0, SUM(value))
FROM
    (SELECT 'Monday' AS day UNION SELECT 'Tuesday' UNION SELECT 'Wednesday' UNION SELECT 'Thursday' UNION SELECT 'Friday' UNION SELECT 'Saturday' UNION SELECT 'Sunday') AS days
    LEFT JOIN (
        SELECT * FROM acx_time_records
        WHERE 
            acx_time_records.state = 3
            AND record_date >= '2012-10-1' AND record_date <= '2012-10-7'    
            AND user_id = 7 
    ) AS acx_time_records
        ON DAYNAME(record_date) = days.day
GROUP BY
    days.day
ORDER BY weekday(acx_time_records.record_date)

这将导致选择一周中的每一天(作为单独的行),并且SUM()对于每一天,0如果没有定义天,将相应地分组。

于 2012-10-09T03:52:04.773 回答