SQL服务器|在列中选择所有特定的重复项

时间:2019-01-23 11:10:58

标签: sql sql-server-2014

我现在的问题是我需要发表一条声明,选择所有有特定需求的重复行。

例如,我得到了表1(用户):

Users:
----------------------------------------------
ID  name   lastname   birth       file number
1   Max    Lix        2015-02-01  D43-892
2   Chris  Maura      2010-12-25  E33-722
4   Lena   Paul       2005-05-11  S85-458
5   Max    Lix        2019-02-01  D23-992
6   Lena   Paul       2005-05-11  S84-488
7   Lena   Paul       2005-05-11  S75-258
----------------------------------------------

Address(u_ID = ID of Users table):
----------------------------------------------
ID   u_ID   Street   number   zip
1    1      Heystr.  12       4556
2    2      Nostr.   2        8978
3    4      Yesstr.  8a       2545

我需要获取姓名,姓氏和出生与其他行完全匹配的所有行,并获取该人的地址。

结果应如下所示:

 Result:
 ----------------------------------------------
 name   lastname   birth       filenumber   address
 Max    Lix        2015-02-01  D43-892      Heystr. 12 4556
 Max    Lix        2019-02-01  D23-992      Heystr. 12 4556
 Lena   Paul       2005-05-11  S85-458      Yesstr. 8a 2545
 Lena   Paul       2005-05-11  S84-488      Yesstr. 8a 2545
 Lena   Paul       2005-05-11  S75-258      Yesstr. 8a 2545

我的第一个想法是使用GROUP BY和HAVING,但是它只返回一行,但是我需要每一个与名称,姓氏和出生匹配的重复项。

4 个答案:

答案 0 :(得分:1)

使用此:

select u.name, u.lastname, u.birth, u.filenumber, concat(a.street, ' ', a.number, ' ', a.zip) address
from users u
left join address a
on a.u_id = u.id
where 
  exists (
    select 1 from users 
    where users.name = u.name and user.lastname = u.lastname and user.birth = u.birth and users.id <> u.id
)

条件:

users.name = u.name and user.lastname = u.lastname and user.birth = u.birth and users.id <> u.id

您可以找到dupilcates。
如果您只希望重复一次,请使用inner join代替left join

答案 1 :(得分:1)

SELECT name, lastname, birth, filenumber, concat(street,' ' , number, ' ', zip) as address
  FROM Users A, Adress
 WHERE u_id = a.id
   AND (SELECT COUNT(1)
          FROM Users B
         WHERE A.name = B.name
           AND A.lastname = B.lastname) > 1

答案 2 :(得分:0)

with duplicate as ( -- this CTE makes a list of duplicated user_IDs

   Select u.id
    from users 
    group by name, lastname, birth
    having count(*) >= 2
)

    Select concat(street,' ' , number, ' ', zip) as address, 
           name, lastname, birth, filenumber 
    from duplicates d -- gather the data
                      join addresses on d.id=uid 
                      join users on u.id=d.uid

将向您返回所有具有相同生日的谐音的人的报告

答案 3 :(得分:0)

请尝试以下

  select U.name,U.lastname,U.birth,U.filenumber,concat(street,' ',number,' ',zip) as address
    from Users U join Address A on 
    U.ID=A.u_Id
    group by name,lastname,birth
    having count(*)>1