如何在多列

时间:2018-01-31 19:34:21

标签: sql

我正在寻找多列中存在重复值的记录。例如:

| id  |column1 | column2|  column3  | column4|  
| 1   | 1      | main   |  101      |   234  |
| 2   | 1      | main   |  101      |   234  |
| 3   | 2      | main   |  101      |   234  |
| 4   | 2      | main   |  103      |   234  |

我想查看column1,column2,column3和column4上匹配的位置。  我不希望在id上匹配。应返回以下内容:

| id  |column1 | column2|  column3  | column4|  
| 1   | 1      | main   |  101      |   234  |
| 2   | 1      | main   |  101      |   234  | 

其他2将不会被返回,因为它们在其中一列上不匹配。

4 个答案:

答案 0 :(得分:1)

您可以使用GROUP BY和COUNT来识别重复项:

SELECT COUNT(id) as duplicates
,column1 
,column2
,column3
,column4
FROM mytable
GROUP BY column1  , column2 , column3 , column4
HAVING COUNT(id) > 1;

答案 1 :(得分:0)

一种方法使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t.column1 = t2.column1 and
                    t.column2 = t2.column2 and
                    t.column3 = t2.column3 and
                    t.column4 = t2.column4
             );

请注意,如果任何列为NULL,则无效。

您可以使用窗口函数L

处理NULL值
select t.*
from (select t.*,
             count(*) over (partition by column1, column2, column3, column4) as cnt
      from t
     ) t
where cnt > 1
order by column1, column2, column3, column4;

答案 2 :(得分:0)

尝试这样的事情,我无法测试这个。所以我不是百分之百,如果这将有效。

Select Id,column1, column2,column3,column4  
From Table 1 t1
Join (
       select column1, column2,column3,column4 From table 1
       Group by column1, column2,column3,column4 
        having Count(*) >1 
     ) dup on dup.column1 = t1.column1 and 
              dup.column2 = t1.column2 and 
              dup.column3 = t1.column3 and 
              dup.column4 = t1.column4 

这应该显示所有带有重复列的ID

答案 3 :(得分:0)

没有子查询并且存在。

SELECT
    t1.id, 
    t1.column1, 
    t1.column2, 
    t1.column3
FROM
    table t1
LEFT JOIN
    table t2 ON 
    t1.column1 = t2.column1 AND 
    t1.column2 = t2.column2 AND 
    t1.column3 = t2.column3 AND 
    t1.id <> t2.id
WHERE
    t2.id IS NOT NULL
GROUP BY
    t1.id, t1.column1, t1.column2, t1.column3