MYSQL:在group by子句中获取零值

时间:2015-12-02 12:00:33

标签: mysql

我还需要在group by子句中使用零值。在Stackoverflow上阅读几乎所有与此相关的问题,但没有一个解决方案有效。

我的表是

enter image description here

需要获得按月份分组的总分。但是我没有得到零表反对表中没有的日子

SELECT SUM(engagement_score), DAY(creation_dt)
FROM qee_emp_engagement_index
RIGHT JOIN (
SELECT 1 AS index1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) AS a ON a.index1 =  DAY(creation_dt)
WHERE org_id = 1
GROUP BY a.index1
ORDER BY a.index1 ASC

3 个答案:

答案 0 :(得分:1)

我会使用left join而不是right join来编写查询(left join的逻辑对我来说更有意义:保留第一个表中的所有行)。但是,您的问题是where子句。该逻辑应该放在on子句中:

SELECT COALESCE(SUM(eei.engagement_score), 0), a.index1
FROM (SELECT 1 AS index1 UNION ALL
      SELECT 2 UNION ALL
      SELECT 3 UNION ALL
      SELECT 4 UNION ALL
      SELECT 5 UNION ALL
      SELECT 6 UNION ALL
      SELECT 7 UNION ALL
      SELECT 8 UNION ALL
      SELECT 9
     ) a LEFT JOIN
     qee_emp_engagement_index eei
     ON a.index1 =  DAY(eei.creation_dt) AND eei.org_id = 1
GROUP BY a.index1
ORDER BY a.index1 ASC;

此外,GROUP BYSELECT应使用驾驶表中的列。

答案 1 :(得分:0)

SELECT DATE(creation_date), SUM(engagement_score) FROM table_name GROUP BY DATE(creation_date)

没有必要在您的代码中加入奇怪的权利

如果您想按月份而不是按日期对其进行分组,请使用DAY()代替DATE()

修改 如果您希望在月份的某一天不存在时为零,请尝试以下操作:

    SELECT d, SUM(score) FROM
 ((SELECT creation_date AS d, engagement_score AS score FROM table_name) 
UNION ALL
(SELECT d, 0 AS engagement_score FROM table_name WHERE d BETWEEN 1 AND 31)) 
GROUP BY d

答案 2 :(得分:0)

您可以在表和包含范围内所有日期的临时表之间进行正确连接。

可以使用以下查询生成日期

select a.Date 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date between '2015-01-01' and '2017-01-01'