[英]SQL select all items with the same column values
So here is the output of my current query:所以这是我当前查询的输出:
ID ![]() |
Col1![]() |
Col2 ![]() |
---|---|---|
871 ![]() |
1 ![]() |
1 ![]() |
646 ![]() |
1 ![]() |
Null![]() |
1223 ![]() |
8 ![]() |
1 ![]() |
1223 ![]() |
8 ![]() |
2 ![]() |
1223 ![]() |
8 ![]() |
3 ![]() |
1224 ![]() |
1 ![]() |
1 ![]() |
1224 ![]() |
1 ![]() |
2 ![]() |
What I'd like to do is only keep the rows which satisfy the following:我想要做的只是保留满足以下条件的行:
For this table, the only rows which should remain are the ones with IDs 646 and 1223.对于这个表,唯一应该保留的行是 ID 为 646 和 1223 的行。
I tried the following where
clause, however it's improperly retaining the bottommost row: (Col2 is null and Col1 is not null) or (Col1 <> Col2)
.我尝试了以下
where
子句,但是它不正确地保留了最底部的行: (Col2 is null and Col1 is not null) or (Col1 <> Col2)
。 Any help appreciated!!任何帮助表示赞赏!
You can do this:你可以这样做:
select *
from my_table
where (Col2 is null and Col1 is not null)
or (id not in (select id
from my_table
where Col1 = Col2)
)
db-fiddle here: https://www.db-fiddle.com/f/xmufn82r9W522YiKKh1Qka/0 db-fiddle 在这里: https : //www.db-fiddle.com/f/xmufn82r9W522YiKKh1Qka/0
I would firstly mark the IDs and col1 of bad rows, then filter the table using these marked rows:我会首先标记坏行的 ID 和 col1,然后使用这些标记的行过滤表:
WITH marked AS
(
SELECT DISTINCT ID, Col1
FROM table
WHERE Col1 = Col2 OR Col1 IS NULL AND Col2 IS NULL
)
SELECT ID
FROM table t1
LEFT JOIN marked t2 ON t1.ID = t2.ID AND t1.Col1 = T2.ColId
WHERE t2.ID IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.