目前有sql返回结果集如下
WORKFLOWID UNMATCHEDVALUE MATCHEDADDRESS EXCEPTIONREASON
1001 UNIQUE ADDRESS1 (null)
1001 UNIQUE ADDRESS2 Some Value
我正在寻找的是像这样的结果
WORKFLOWID UNMATCHEDVALUE MATCHEDADDRESS EXCEPTIONREASON MATCHEDADDRESS2 EXCEPTIONREASON2
1001 UNIQUE ADDRESS1 (null) ADDRESS2 Some Value
因此“variant”列是MatchedAddress和Exception Reason,其他列对于每条记录都是相同的。请注意,对于每个workflow_id,将始终返回2行。
我还创建了一个显示模式的小提琴。
答案 0 :(得分:4)
试试这个:
;WITH CTE AS
(
SELECT ws.id as WorkflowStepId,
ws.workflow_id as WorkflowId,
sg.unmatchValue as UnmatchedValue,
geo_address as MatchedAddress,
ws.exception_Value as ExceptionReason,
ROW_NUMBER() OVER(PARTITION BY ws.workflow_id ORDER BY ws.id) as RN
FROM workflow_step as ws
INNER JOIN workflow as gw
ON ws.workflow_id = gw.id
INNER JOIN super_group as sg
ON gw.super_group_id = sg.id
INNER JOIN alias on
ws.id = alias.workflow_step_id
)
SELECT WorkflowId,
UnmatchedValue,
MIN(CASE WHEN RN = 1 THEN MatchedAddress END) MatchedAddress,
MIN(CASE WHEN RN = 1 THEN ExceptionReason END) ExceptionReason,
MIN(CASE WHEN RN = 2 THEN MatchedAddress END) MatchedAddress2,
MIN(CASE WHEN RN = 2 THEN ExceptionReason END) ExceptionReason2
FROM CTE
GROUP BY WorkflowId,
UnmatchedValue
ORDER BY workflowId
Here is修改后的sqlfiddle。
结果是:
╔════════════╦════════════════╦════════════════╦═════════════════╦═════════════════╦══════════════════╗
║ WORKFLOWID ║ UNMATCHEDVALUE ║ MATCHEDADDRESS ║ EXCEPTIONREASON ║ MATCHEDADDRESS2 ║ EXCEPTIONREASON2 ║
╠════════════╬════════════════╬════════════════╬═════════════════╬═════════════════╬══════════════════╣
║ 1001 ║ UNIQUE ║ ADDRESS1 ║ (null) ║ ADDRESS2 ║ Some Value ║
╚════════════╩════════════════╩════════════════╩═════════════════╩═════════════════╩══════════════════╝
答案 1 :(得分:0)
试试这个:
SELECT ws.workflow_id as WorkflowId, sg.unmatchValue as UnmatchedValue,
MAX(CASE WHEN ws.id = 1 THEN geo_address END) as MatchedAddress1,
MAX(CASE WHEN ws.id = 2 THEN geo_address END) as MatchedAddress2,
MAX(CASE WHEN ws.id = 1 THEN ws.exception_Value END) as ExceptionReason1,
MAX(CASE WHEN ws.id = 2 THEN ws.exception_Value END) as ExceptionReason2
FROM workflow_step as ws
INNER JOIN workflow as gw on ws.workflow_id = gw.id
INNER JOIN super_group as sg on gw.super_group_id = sg.id
inner JOIN alias on ws.id = alias.workflow_step_id
GROUP BY ws.workflow_id, sg.unmatchValue
答案 2 :(得分:0)
由于我无法评论,我只是想指出,Lamak给出的答案是使用Common Table Expression。这些通常是解决sql中递归问题的最佳选择。
答案 3 :(得分:0)
这假设您只有2种地址类型。如果您有更多,我建议您创建一个数据透视表。
select a.*, MATCHEDADDRESS2,EXCEPTIONREASON2
from
(Select WORKFLOWID,UNIQUEVALUE,MATCHEDADDRESS,EXCEPTIONREASON
from "Your Table"
where MATCHEDADDRESS='ADDRESS1') a
join
(Select WORKFLOWID,UNIQUEVALUE,MATCHEDADDRESS as MATCHEDADDRESS2,EXCEPTIONREASON as XCEPTIONREASON2
from "Your Table"
where MATCHEDADDRESS='ADDRESS2') b
on a.WORKFLOWID=b.WORKFLOWID
and a.UNMATCHEDVALUE = b.UNMATCHEDVALUE