mysql:将不存在的数据连接到一个表并求和

xzv2uavs  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(285)

我有这样的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:

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 |

我试着选择a和b的总和,从1到12,即使表a上的月份不存在,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将month sql与tablea连接起来,但是结果不正确。

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

任何帮助都会很好。

b1payxdu

b1payxdu1#

where tableA.YEAR=2016

当您对任何列tablea设置条件时,只有tablea.year不为null的行才能通过该条件。因此,从外部联接中消除了不匹配的行。
把这个条件放在你的加入…条件。

相关问题