简体   繁体   English

SQL 选择具有相同列值的所有项目

[英]SQL select all items with the same column values

So here is the output of my current query:所以这是我当前查询的输出:

ID ID Col1第 1 列 Col2 Col2
871 871 1 1 1 1
646 646 1 1 Null空值
1223 1223 8 8 1 1
1223 1223 8 8 2 2
1223 1223 8 8 3 3
1224 1224 1 1 1 1
1224 1224 1 1 2 2

What I'd like to do is only keep the rows which satisfy the following:我想要做的只是保留满足以下条件的行:

  • Col2 is Null; Col2 为空; or或者
  • ID+Col1 == Col2 for one of the rows with the same ID, eg, the bottom two rows are not included because the second from the bottom Col1==Col2 and the bottommost is not included because the ID and Col1 match the second from the bottom in which Col1==Col2. ID+Col1 == Col2 对于具有相同 ID 的行之一,例如,不包括底部两行,因为从底部开始的第二行 Col1==Col2 和最底部不包括在内,因为 ID 和 Col1 匹配从Col1==Col2 的底部。

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 

Your logic can be applied with NOT EXISTS :您的逻辑可以应用于NOT EXISTS

SELECT t1.*
FROM tablename t1
WHERE t1.Col2 IS NULL
   OR NOT EXISTS (
     SELECT 1 
     FROM tablename t2
     WHERE t2.Col1 = t2.Col2 AND t2.ID = t1.ID
   );

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM