将不存在或不存在的数据规范化为单个 SQL 查询

Normalize data with no matter exist or no exist into single SQL query

我的 table TblFinishByClass 中有这条记录。一些ID没有参加Class,因此没有记录存在。只有 3 class 个可用,分别是 C、TP 和 TT。

ID        Class    Month     Year    Finished    Total 
ASAN014    C        04       2020      12         19
ASAN014    TP       04       2020      4          6
ASAN014    TT       04       2020      2          7
ASAN014    C        05       2020      10         18
ASAN014    TP       05       2020      1          2
ASAN014    TT       05       2020      2          6
ASAN015    C        04       2020      21         24
ASAN015    TP       04       2020      0          1
ASAN015    TT       04       2020      8          11
ASAN015    C        05       2020      14         19
ASAN015    TT       05       2020      4          5

如前所述。如果 ASAN015 不参加 TT 的 class,则 FinishedTT 和 TotalTT 的数据默认值应为零。我需要按 ID、月份和年份对其进行分组,其中它将如下所示 table:

ID        Month    Year   FinishedC TotalC   FinishedTP  TotalTP  FinishedTT  TotalTT
ASAN014     04     2020      12      19          4        6         2          7
ASAN014     05     2020      10      18          1        2         2          6
ASAN015     04     2020      21      24          0        1         8          11
ASAN015     05     2020      14      19          4        5         0          0

我的问题是我们可以在一次查询中完成吗?

您可以使用条件聚合。

SELECT
    ID,
    Month,
    Year,
    SUM(CASE WHEN Class = 'C' THEN Finished ELSE 0 END) AS FinishedC,
    SUM(CASE WHEN Class = 'C' THEN Total ELSE 0 END) AS TotalC,
    SUM(CASE WHEN Class = 'TT' THEN Finished ELSE 0 END) AS FinishedTT,
    SUM(CASE WHEN Class = 'TT' THEN Total ELSE 0 END) AS TotalTT,
    SUM(CASE WHEN Class = 'TP' THEN Finished ELSE 0 END) AS FinishedTP,
    SUM(CASE WHEN Class = 'TP' THEN Total ELSE 0 END) AS TotalTP
FROM 
 TblFinishByClass
GROUP BY
    ID,
    Month,
    Year;

结果:

+----+---------+-------+------+-----------+--------+------------+---------+------------+---------+
|    |   ID    | Month | Year | FinishedC | TotalC | FinishedTT | TotalTT | FinishedTP | TotalTP |
+----+---------+-------+------+-----------+--------+------------+---------+------------+---------+
|  1 | ASAN014 |     4 | 2020 |        12 |     19 |          2 |       7 |          4 |       6 |
|  2 | ASAN014 |     5 | 2020 |        10 |     18 |          2 |       6 |          1 |       2 |
|  3 | ASAN015 |     4 | 2020 |        21 |     24 |          8 |      11 |          0 |       1 |
|  4 | ASAN015 |     5 | 2020 |        14 |     19 |          4 |       5 |          0 |       0 |
+----+---------+-------+------+-----------+--------+------------+---------+------------+---------+