【问题标题】:How can I get record which has same value in two column?如何获得在两列中具有相同值的记录?
【发布时间】:2021-11-03 17:42:11
【问题描述】:

在此表中,我有 3 列名姓氏和年龄。在这个表中有一些重复的记录。例如,在两条记录中,名字和姓氏相同,只是年龄不同。我想通过 SQL 查询获得类似的记录。如何获取具有相同名字和相同姓氏的记录。

样本数据

我想获取所有名字为 john 且姓氏为 doe 的记录。

【问题讨论】:

  • Select * from Table where FirstName='john' and LastName='doe';
  • @sojin no john doe 只是样本。在该表中有许多具有相同名字和姓氏的记录。我想获得所有相同的记录,不仅是 john doe。
  • 根据问题指南,请展示您尝试过的内容并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。并且请不要发布代码、数据、错误消息等的图像 - 将文本复制或输入到问题中。请保留将图像用于图表或演示渲染错误,无法通过文本准确描述的事情。
  • I want to get all record which has john as first name and has doe as lastname。如果这不是您想要的,请不要将其写入您的问题中。
  • 真正的问题是寻找“重复”吗?

标签: sql sql-server tsql


【解决方案1】:

这是一个查询,它为您提供所有具有相同名称但不同或相同年龄的记录

Select *, 
   rn =dense_rank() 
        over (partition by firstname, lastname order by age asc) 
from yourtable

这为具有相同名称的所有记录提供相同的排名(rn 列)值。现在,如果您需要表中具有相同名称的所有记录。

select * from 
(
    Select *, 
       rn =dense_rank() 
            over (partition by firstname, lastname order by age asc) 
    from yourtable
) T
where firstname =@firstname and lastname =@lastname

【讨论】:

    【解决方案2】:

    一种非常“自然”的阅读方式是询问“对于所有行,是否有另一行(即具有不同 id 的行)具有相同的名字和姓氏”:

    select t.id, t.firstName, t.lastName, t.age
    from   MyTable t
    where  exists  
           (
              select *
              from   MyTable
              where  firstName = t.firstName
                     and lastName = t.lastName
                     and id != t.id
           )
    

    【讨论】:

      【解决方案3】:

      您可以在此处使用嵌套查询和count 函数

      假设表名是users

      select * from users 
          where (select count(id) from users as nested_users 
                  where nested_users.FirstName=users.FirstName 
                  and nested_users.LastName=users.LastName) > 1;
      

      nested_users 是别名

      【讨论】:

      • 没有 john doe 只是样本。在该表中有许多具有相同名字和姓氏的记录。我想获得所有相同的记录,不仅是 john doe。
      • @Can 好的,我知道你的问题了。我已经更新了我的答案。
      【解决方案4】:
      select user1.*     
               from User user1 , User user2
                   where user1.firstName = user2.firstName 
                         and user1.lastName = user2.lastName 
                         and user1.id != user2.id
      

      【讨论】:

      • 如果您有新问题,请点击 按钮提出问题。如果有助于提供上下文,请包含指向此问题的链接。 - From Review
      • @krystanhonour:是什么让你认为这是一个新问题?
      【解决方案5】:
      SELECT FirstName, LastName, COUNT(*)
      FROM Table
      GROUP BY FirstName
      HAVING (COUNT(*) > 1);
      

      此查询将返回具有重复项的数据并显示重复项总数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-10
        • 2013-09-06
        • 2020-05-20
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多