我所拥有的:表
_______________________________________
| 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')
但是,这会返回一个奇怪的联合,看起来像:
我得到的输出错误
| MachUUID | A_Pass| A_Fail |
| 1234 | 0.2 | 0.98 |
| 1234 | 0.5 | 0.5 |
| 1234 | 0.8 | 0.2 |
问题
我认为我对工会的理解在这一点上是不正确的。我了解externaljoins,并想知道这是否是更好的方法。
我愿意提出其他解决方法的建议
答案 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