在多列中查找具有相同值的行

时间:2022-02-24 13:01:16

I am trying to find rows that have duplicate values, but only based off of a select number of columns, not a single column or the entire row. For example, if my table looked like this:

我试图找到具有重复值的行,但仅基于选定数量的列,而不是单个列或整个行。例如,如果我的表看起来像这样:

ID     Address    State    Name
-------------------------------
0      7 Brown    NY       John
1      3 Red      WX       Jane
2      7 Brown    WX       Ted
3      7 Brown    NY       Fred

My question would be:

我的问题是:

Find all ID's for rows where the row's Address and State field matched another row's Address and State field.

查找行的地址和状态字段与另一行的地址和状态字段匹配的行的所有ID。

The answer to this query would be:

这个查询的答案是:

ID    Address    State    Name
------------------------------
0     7 Brown    NY       John
3     7 Brown    NY       Fred

Any Ideas?

有任何想法吗?

Suggestions: How to select multiple columns values same rows from single table

建议:如何从单个表中选择多个列值相同的行

2 个解决方案

#1


29  

Try the following:

请尝试以下方法:

SELECT A.*
FROM YourTable A
INNER JOIN (SELECT Address, State
            FROM YourTable
            GROUP BY Address, State
            HAVING COUNT(*) > 1) B
ON A.Address = B.Address AND A.State = B.State

#2


2  

select *
from #table1
where Addr + St in (select Addr + St as FullAddr
             from #table1
             group by Addr + St
             having count(Addr+St) > 1)

#1


29  

Try the following:

请尝试以下方法:

SELECT A.*
FROM YourTable A
INNER JOIN (SELECT Address, State
            FROM YourTable
            GROUP BY Address, State
            HAVING COUNT(*) > 1) B
ON A.Address = B.Address AND A.State = B.State

#2


2  

select *
from #table1
where Addr + St in (select Addr + St as FullAddr
             from #table1
             group by Addr + St
             having count(Addr+St) > 1)