我有一个要透视的桌子。我可以部分实现我想要的。我需要帮助才能完成
我的基本表
+-------------+----------+-------------+
| WorkOrderID | STEP_NBR | STEP_STATUS |
+-------------+----------+-------------+
| AA100 | 0 | C |
| AA100 | 1 | W |
| AA100 | 2 | W |
| AA200 | 0 | W |
| AA200 | 1 | W |
| AA300 | 0 | C |
| AA300 | 1 | C |
+-------------+----------+-------------+
我想要的输出
+-------------+--------+--------+--------+
| WorkOrderID | Step_0 | Step_1 | Step_2 |
+-------------+--------+--------+--------+
| AA100 | C | W | W |
| AA200 | W | W | |
| AA300 | C | C | |
+-------------+--------+--------+--------+
我得到的输出
+-------------+--------+--------+--------+
| WorkOrderID | Step_0 | Step_1 | Step_2 |
+-------------+--------+--------+--------+
| AA100 | C | null | null |
| AA100 | null | W | null |
| AA100 | null | null | W |
| AA200 | W | null | null |
| AA200 | null | W | null |
| AA300 | C | null | null |
| AA300 | null | C | null |
+-------------+--------+--------+--------+
我的查询
SELECT WorkOrderID,
(CASE WHEN STEP_NBR = 0 THEN STEP_STATUS ELSE NULL END) AS Step_0,
(CASE WHEN STEP_NBR = 1 THEN STEP_STATUS ELSE NULL END) AS Step_1,
(CASE WHEN STEP_NBR = 2 THEN STEP_STATUS ELSE NULL END) AS Step_2
FROM Table1
如何摆脱多个WorkOrderId。我只需要每个WorkOrderId 1行
答案 0 :(得分:3)
您只需要聚合:
SELECT WorkOrderID,
MAX(CASE WHEN STEP_NBR = 0 THEN STEP_STATUS END) AS Step_0,
MAX(CASE WHEN STEP_NBR = 1 THEN STEP_STATUS END) AS Step_1,
MAX(CASE WHEN STEP_NBR = 2 THEN STEP_STATUS END) AS Step_2
FROM Table1
GROUP BY WorkOrderID;
ELSE NULL
是多余的,因此我将其删除。