SQL-考虑类型的多行总和

时间:2018-11-13 14:10:55

标签: mysql sql

我有一张看起来像下面的表:

+========================================================+
|    Number   |    Date     |    Liter    |     Type      |
+=========================================================+
|       1     | 2018-11-01  |      1.0    |       A       |
|       2     | 2018-11-01  |      2.0    |       A       |
|       3     | 2018-11-01  |      3.0    |       B       |
|       1     | 2018-11-02  |      4.0    |    NULL       |
|       2     | 2018-11-02  |      5.0    |       B       |
|       3     | 2018-11-02  |      6.0    |    NULL       |
|       1     | 2018-11-03  |      7.0    |       B       |
|       2     | 2018-11-03  |      8.0    |       B       |
|       3     | 2018-11-03  |      9.0    |    NULL       |
+---------------------------------------------------------+

我需要使用WHERE Date LIKE '2018-11-%'

+========================================================+
|  Number  |  SumOfTypeA  |  SumOfTypeB  |  SumOfTypeNULL |
+=========================================================+
|     1    |      1.0     |      7.0     |       4.0      |
|     2    |      2.0     |     13.0     |      NULL      |
|     3    |     NULL     |      3.0     |      15.0      |
+---------------------------------------------------------+

对此查询有何建议?

1 个答案:

答案 0 :(得分:0)

您可以使用SUM()CASE..WHEN表达式进行条件聚合:

SELECT
  Number,
  SUM(CASE WHEN Type = 'A' THEN Liter END) AS SumOfTypeA,
  SUM(CASE WHEN Type = 'B' THEN Liter END) AS SumOfTypeB,
  SUM(CASE WHEN Type IS NULL THEN Liter END) AS SumOfTypeNull
FROM your_table
WHERE Date LIKE '2018-11-%'
GROUP BY Number