簡體   English   中英

使用案例語句作為樞軸 - DB2 SQL

[英]Using Case Statements As a Pivot - DB2 SQL

我想要一份汽車運輸車清單,拖車設備數量列在不同的欄目中。 我使用case語句對不同的設備類型進行分類,但是我得到了多次返回,而不是每個運營商看到一次返回。

我試過ROW OVER()並得到相同的結果。

SELECT C.ECP_CARRIER_IDENT_ID AS ECP_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'TR' THEN E.EQUIPMENT_CT END) AS TRACTORS,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'SV' THEN E.EQUIPMENT_CT END) AS VAN_TRLS,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'FT' THEN E.EQUIPMENT_CT END) AS FLATBEDS
FROM ECP_CARRIER C
JOIN ECP_CARRIER_EQUIPMENT E ON C.ECP_CARRIER_IDENT_ID = E.ECP_CARRIER_ID
WHERE CERTIFIED_FG = 1
GROUP BY C.ECP_CARRIER_IDENT_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
E.EQUIPMENT_TYPE_CD, E.EQUIPMENT_CT

我希望一切都在一排,但這是我得到的結果

ECP_NB   CARRIER_NM     MC_NB    DOT_NB  TRACTORS VAN_TRLS   FLATBEDS
 1234   Bob's Trucking   606066     66    10               
 1234   Bob's Trucking   606066     66              12

使用聚合函數並group by以下方式修復group by

SELECT C.ECP_CARRIER_IDENT_ID AS ECP_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'TR' THEN E.EQUIPMENT_CT END) AS TRACTORS,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'SV' THEN E.EQUIPMENT_CT END) AS VAN_TRLS,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'FT' THEN E.EQUIPMENT_CT END) AS FLATBEDS
FROM ECP_CARRIER C JOIN
     ECP_CARRIER_EQUIPMENT E
     ON C.ECP_CARRIER_IDENT_ID = E.ECP_CARRIER_ID
WHERE CERTIFIED_FG = 1
GROUP BY C.ECP_CARRIER_IDENT_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB;

GROUP BY的鍵組合應定義結果集中所需的每一行。 您不需要E.EQUIPMENT_TYPE_CD (例如)的單獨行,因此它不應該在GROUP BY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM