简体   繁体   English

使用SQL查询查找多列相同的行

[英]find rows that multiple columns are identical using SQL query

I have to write a query to get a result set from table T 我必须编写查询以从表T中获取结果集

where table T is defined as 其中表T定义为

  • Primary Key 首要的关键
  • column A A栏
  • column B B栏
  • column C C栏

I need to get the rows that have the same value in column As and also have same value in column Cs. 我需要获取在As列中具有相同值并且在Cs列中也具有相同值的行。 How to write the query? 如何编写查询? (using generic SQL query) (使用通用SQL查询)

Use: 采用:

SELECT a.PrimaryKey, b.PrimaryKey
  FROM T a
 INNER JOIN T b
    ON a.columnA = b.columnA
   AND a.columnC = b.columnC
   AND a.PrimaryKey < b.PrimaryKey

This will give all couples of rows (only one time with the inequality clause). 这将给出所有两行(仅一次使用inequality子句)。

If that is too much (having three pairs A–B, A–C, B–C) it is also possible with standard SQL to restrict to the case where the left key is the minimal key for the group (you will then get only A–B and A–C): 如果太多(具有三对A–B,A–C,B–C),则也可以使用标准SQL将左键限制为该组的最小键的情况(然后,您将仅获得A–B和A–C):

SELECT a.PrimaryKey, b.PrimaryKey
  FROM T a
 INNER JOIN T b
    ON b.columnA = a.columnA
   AND b.columnC = a.columnC
  LEFT JOIN T c
    ON c.columnA = a.columnA
   AND c.columnC = a.columnC
   AND c.PrimaryKey < a.PrimaryKey
 WHERE a.PrimaryKey < b.PrimaryKey
   AND c.PrimaryKey IS NULL

To find the tuples A,C that have duplicate in table you can use 要查找表中重复的元组A,C,可以使用

SELECT A, C, count(*)
FROM T
GROUP BY A, C
HAVING count(*) >=2

Now you can select all rows from table T that have A, C in this "duplicates" set. 现在,您可以从表T中选择在此“重复项”集中具有A,C的所有行。

Select PrimaryKey, A, B, C 
FROM T JOIN 
 (SELECT A, C, count(*)
  FROM T
  GROUP BY A, C
  HAVING count(*) >=2
 ) dupl
on T.A = dupl.A and T.C = dupl.C

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

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