首页 > 解决方案 > 根据多列查找重复项

问题描述

我需要找到所有在不同位置重复的行。表数据如下,

---------------------------------------------------------
| Assetno  |  SerialNo  |   StickerNo  |     location  |
---------------------------------------------------------
| 1234     |   QWR      |   12ERT      |     123       |
| 1234     |   QWR      |   12ERT      |     567       |
| 7888     |   ytu      |   67UI       |     456       |
| 9000     |   UIO      |   OPIO9      |     8         |
---------------------------------------------------------

像上表一样,我需要找到行号 1 和 2 之类的行。

标签: sqlsql-server

解决方案


一种方法使用窗口函数。因此,这适用于您的示例数据:

select t.*
from (select t.*,
             count(*) over (partition by Assetno, SerialNo, StickerNo) as cnt
      from t
     ) t
where cnt >= 2;

不过,我会更倾向于使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.Assetno = t.Assetno and
                    t2.SerialNo = t.SerialNo and
                    t2.StickerNo = t.StickerNo and
                    t2.location <> t.location
             );

这更明确地指定前三列相同的行具有不同的位置。使用索引也可能更快(Assetno, SerialNo, StickerNo, location)


推荐阅读