我有一个类似于以下内容的数据集:
| ID | Match1 | Match2 | Key | Val1 |
| 1 | a | b | a | a |
| 2 | a | b | c | b |
| 3 | a | b | keep | c |
| 4 | a | a | a | d |
您将看到1-3行在Match1和Match2中具有匹配值,而第3行在Key列中具有“ keep”。
我正在尝试编写一个查询,该查询将根据匹配条件删除第1行和第2行,但由于提供了键,因此保留了第3行。结果数据集如下所示:
| ID | Match1 | Match2 | Key | Val1 |
| 3 | a | b | keep | c |
| 4 | a | a | a | d |
关于如何进行这项工作的任何建议?
答案 0 :(得分:0)
让我猜测:您希望每match1
/ match2
组合使用一行,并且优先选择“保持”。如果是这样:
select t.*
from t
where t.id = (select t2.id
from t t2
where t2.match1 = t.match1 and t2.match2 = t.match2
order by (key = 'keep') desc, -- highest preference for "keep"
id desc -- most recent id
limit 1
);
要处理NULL
,可以使用NULL
安全比较:
select t.*
from t
where t.id = (select t2.id
from t t2
where t2.match1 <=> t.match1 and t2.match2 <= >t.match2
order by (key = 'keep') desc, -- highest preference for "keep"
id desc -- most recent id
limit 1
);