外部联接或联合所有以将行转换为列

Outer join or union all to transform the rows into columns

我有: table

 _______________________________________            
 | MachUUID | State|  Pass   | Fail    |   
 |--------------------------------------
 |  1234    | A    |   0.2   |    0.98 |  
 |  1234    | B    |   0.5   |    0.5  |  
 |  1234    | C    |   0.8   |    0.2  |
 ---------------------------------------

我想要什么:transformed_table

 | MachUUID | A_Pass | A_Fail | B_Pass | B_Fail | C_Pass | C_Fail
  --------------------------------------------------------------
 |  1234    |  0.2   | 0.98   |  0.5   |  0.5   | 0.8    |  0.2 

状态数(A、B等是固定的)。目前他们最多有 20 个。所以要改造这个

我在做什么:

Transformed_Table AS (
SELECT MachUUID, Pass AS A_Pass, Fail AS A_Fail
FROM table
WHERE State = 'A'
UNION ALL

SELECT MachUUID, Pass AS B_Pass, Fail AS B_Fail
FROM table
WHERE State = 'B'
UNION ALL

SELECT MachUUID, Pass AS C_Pass, Fail AS C_Fail
FROM table
WHERE State = 'C')

然而,这个 returns 一个奇怪的联盟看起来像:

我得到错误的输出

| MachUUID | A_Pass| A_Fail |
|   1234   | 0.2   | 0.98   |
|   1234   | 0.5   | 0.5    |
|   1234   | 0.8   | 0.2    |

问题

我认为我对联合的理解在这一点上是不正确的。我了解外部连接,想知道这是否是更好的方法。

我愿意接受有关解决此问题的其他方法的建议

您可以使用条件聚合来做到这一点:

select MachUUID,
       max(case when state = 'A' then pass end) as a_pass,
       max(case when state = 'A' then fail end) as a_fail,
       max(case when state = 'B' then pass end) as b_pass,
       max(case when state = 'B' then fail end) as b_fail,
       max(case when state = 'C' then pass end) as c_pass,
       max(case when state = 'C' then fail end) as c_fail
from t
group by MachUUID