我有一个数据库,如图所示。我们以下面的数据为例:
WORKORDER 表:
WONUM (PK) | WORKTYPE | STATUS | DESCRIPTION
1234 URGENT OPEN Inv. work X.
FAILUREREPORT 表:
FAILUREREPORTID (PK) | WONUM | FAILURECODE | ASSETNUM | TYPE
5678 1234 SYMPT1347 DT-JA-123 Problem
5679 1234 WA4521 DT-JA-123 Cause
5680 1234 SOL1672 DT-JA-123 Solution
FAILURECODE 表:
FAILURECODEID (PK) | FAILURECODE | DESCRIPTION
345 SYMPT1347 Symptom X.
346 WA4521 Cause Y.
347 SOL1672 Solution Z.
我有以下查询,它完成了一半的工作:
SELECT F.WONUM, W.DESCRIPTION AS WO_DESC, W.STATUS, F.ASSETNUM, F.TYPE, C.DESCRIPTION AS FCODE_DESC
FROM WORKORDER W
INNER JOIN FAILUREREPORT F ON F.WONUM = W.WONUM
INNER JOIN FAILURECODE C ON F.FAILURECODE = C.FAILURECODE
WHERE W.WORKTYPE = 'URGENT' AND W.STATUS <> 'CANCELLED'
ORDER BY F.WONUM ASC, F.TYPE ASC
它返回:
WONUM | WO_DESC | STATUS | ASSETNUM | TYPE | FCODE_DESC
1234 Inv. work X. OPEN DT-JA-123 PROBLEM Symptom X.
1234 Inv. work X. OPEN DT-JA-123 CAUSE Cause Y.
1234 Inv. work X. OPEN DT-JA-123 SOLUTION Solution Z.
但是,我希望在一行中列出症状,原因和解决方案,而不是3行,如下所示:
WONUM | WO_DESC | STATUS | ASSETNUM | PROBLEM | CAUSE | SOLUTION
1234 Inv. work X. OPEN DT-JA-123 Symptom X. Cause Y. Solution Z.
如果有可能,如何使用pivot功能将行转换为列?我也对任何能够产生预期结果的其他解决方案持开放态度。 我操作的数据库是Oracle DB,而我的游乐场/测试环境是MySQL。我知道不能在MySQL中使用数据透视表,但是通过聚合和分组可以解决这个问题。
答案 0 :(得分:2)
您需要一个案例陈述。试试这个
SELECT F.WONUM,
W.DESCRIPTION AS WO_DESC,
W.STATUS,
F.ASSETNUM,
MIN (CASE WHEN TYPE = 'PROBLEM' THEN C.DESCRIPTION END) AS PROBLEM,
MIN (CASE WHEN TYPE = 'CAUSE' THEN C.DESCRIPTION END) AS CAUSE,
MIN (CASE WHEN TYPE = 'SOLUTION' THEN C.DESCRIPTION END) AS SOLUTION
FROM WORKORDER W
INNER JOIN FAILUREREPORT F ON F.WONUM = W.WONUM
INNER JOIN FAILURECODE C ON F.FAILURECODE = C.FAILURECODE
WHERE W.WORKTYPE = 'URGENT'
AND W.STATUS <> 'CANCELLED'
GROUP BY F.WONUM,
W.DESCRIPTION,
W.STATUS,
F.ASSETNUM
ORDER BY F.WONUM ASC
答案 1 :(得分:1)
使用子查询:
SELECT w.wonum, w.description AS wo_desc, w.status,
(SELECT assetnum FROM FAILUREREPORT WHERE wonum = w.wonum LIMIT 1) assetnum,
(SELECT description
FROM FAILUREREPORT JOIN FAILURECODE USING(failurecode)
WHERE type = 'PROBLEM' AND wonum = w.wonum) problem,
(SELECT description
FROM FAILUREREPORT JOIN FAILURECODE USING(failurecode)
WHERE type = 'CAUSE' AND wonum = w.wonum) cause,
(SELECT description
FROM FAILUREREPORT JOIN FAILURECODE USING(failurecode)
WHERE type = 'SOLUTION' AND wonum = w.wonum) solution
FROM WORKORDER w
WHERE w.worktype = 'URGENT' AND w.status <> 'CANCELLED'
ORDER BY wonum ASC