我的示例数据如下所示:
A1 A2 B1 B2
1 2 2 3
4 5 5 7
5 4 1 4
我的目标是提取这样的数据
result1 result2
1 3
4 7
5 1
这一切都可能吗?提前感谢您的反馈。
答案 0 :(得分:0)
这一切都可能吗?
是的可能(我假设您有一个唯一标识行的列):
SELECT id
,MIN(CASE WHEN g=1 THEN c END) AS result1
,MIN(CASE WHEN g=2 THEN c END) AS result2
FROM (
SELECT id,c,MIN(g) AS g
FROM (SELECT id, A1 AS c, 1 AS g FROM tab UNION ALL
SELECT id, A2, 1 FROM tab UNION ALL
SELECT id, B1,2 FROM tab UNION ALL
SELECT id, B2,2 FROM tab) sub
GROUP BY id, c
HAVING COUNT(*) = 1) s
GROUP BY id;
<强> DBFiddle Demo 强>
输出:
┌────┬─────────┬─────────┐
│ id │ result1 │ result2 │
├────┼─────────┼─────────┤
│ 1 │ 1 │ 3 │
│ 2 │ 4 │ 7 │
│ 3 │ 5 │ 1 │
└────┴─────────┴─────────┘
实际上它更简单:
SELECT CASE WHEN g1_min IN(g2_min, g2_max) THEN g1_max ELSE g1_min END AS result1
,CASE WHEN g2_min IN(g1_min, g1_max) THEN g2_max ELSE g2_min END AS result2
FROM (SELECT LEAST(A1,A2) g1_min,GREATEST(A1,A2) g1_max
,LEAST(B1,B2) g2_min,GREATEST(B1,B2) g2_max
FROM tab) s;
<强> DBFiddle Demo 强>
SELECT CASE WHEN A1 IN (B1, B2) THEN A2 ELSE A1 END AS result1
, CASE WHEN B1 IN (A1, A2) THEN B2 ELSE B1 END AS result2
FROM tab;
<强> DBFiddle Demo 强>
答案 1 :(得分:0)
如果您只有4列,则可以这样做。如果某些行与您的条件不匹配,则会返回-404错误。
select
case
when a1=b1 or a1=b2 then a2
when a2=b1 or a2=b2 then a1
else -404
end as result1,
case
when b1=a1 or b1=a2 then b2
when b2=a1 or b2=a2 then b1
else -404
end as result2
from your_table