MYSQL:将不存在的数据加入 table 并求和

MYSQL: JOIN Non-Exist data to a table and sum it

我有 sql 这样的:

SELECT 
m.MONTH
FROM (
           SELECT '1' AS MONTH
           UNION ALL SELECT '2' AS MONTH
           UNION ALL SELECT '3' AS MONTH
           UNION ALL SELECT '4' AS MONTH
           UNION ALL SELECT '5' AS MONTH
           UNION ALL SELECT '6' AS MONTH
           UNION ALL SELECT '7' AS MONTH
           UNION ALL SELECT '8' AS MONTH
           UNION ALL SELECT '9' AS MONTH
           UNION ALL SELECT '10' AS MONTH
           UNION ALL SELECT '11' AS MONTH
           UNION ALL SELECT '12' AS MONTH
) AS m

这将显示第 1 个月到第 12 个月

我有一个 table 这样的: tableA:

YEAR | MONTH | A | B |
2015 |   1   | 1 | 3 |
2016 |   1   | 2 | 2 |
2013 |   1   | 3 | 2 |
2016 |   2   | 4 | 1 |
2016 |   3   | 5 | 1 |
2016 |   4   | 6 | 3 |

我正在尝试 select 从 1 到 12 对整个月份的 A 和 B 求和,即使 tableA 上的月份不存在以在 2016 年显示为 0。

结果:

预期结果如下:

MONTH | YEAR | SUM_OF_A | SUM_OF_B |
1     | 2016 |    6     |    3     |
2     | 2016 |    0     |    0     |
3     | 2016 |    5     |    1     |
4     | 2016 |    6     |    3     |
5     | 2016 |    0     |    0     |
6     | 2016 |    0     |    0     |
7     | 2016 |    0     |    0     |
8     | 2016 |    0     |    0     |
9     | 2016 |    0     |    0     |
10    | 2016 |    0     |    0     |
11    | 2016 |    0     |    0     |
12    | 2016 |    0     |    0     |

我正在尝试使用以下 SQL 与 tableA 加入月份 SQL,但结果不正确。

SELECT 
m.MONTH, tableA.YEAR, 
CASE WHEN tableA.A is not null THEN sum(tableA.A) ELSE 0 END AS SUM_OF_A,
CASE WHEN tableA.B is not null THEN sum(tableA.B) ELSE 0 END AS SUM_OF_B,
FROM (
           SELECT '1' AS MONTH
           UNION ALL SELECT '2' AS MONTH
           UNION ALL SELECT '3' AS MONTH
           UNION ALL SELECT '4' AS MONTH
           UNION ALL SELECT '5' AS MONTH
           UNION ALL SELECT '6' AS MONTH
           UNION ALL SELECT '7' AS MONTH
           UNION ALL SELECT '8' AS MONTH
           UNION ALL SELECT '9' AS MONTH
           UNION ALL SELECT '10' AS MONTH
           UNION ALL SELECT '11' AS MONTH
           UNION ALL SELECT '12' AS MONTH
) AS m
LEFT OUTER JOIN tableA on m.MONTH = tableA.MONTH
where tableA.YEAR=2016
group by tableA.MONTH

任何帮助都会很棒。

where tableA.YEAR=2016

当您对任何列 tableA 设置条件时,只有 tableA.YEAR 不为 NULL 的行才会通过条件。因此,您从 OUTER JOIN 中删除了不匹配的行。

将该条件放入您的 JOIN...ON 条件中。