sql - 根据多列查找重复项
问题描述
我需要找到所有在不同位置重复的行。表数据如下,
---------------------------------------------------------
| Assetno | SerialNo | StickerNo | location |
---------------------------------------------------------
| 1234 | QWR | 12ERT | 123 |
| 1234 | QWR | 12ERT | 567 |
| 7888 | ytu | 67UI | 456 |
| 9000 | UIO | OPIO9 | 8 |
---------------------------------------------------------
像上表一样,我需要找到行号 1 和 2 之类的行。
解决方案
一种方法使用窗口函数。因此,这适用于您的示例数据:
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)
。
推荐阅读
- tomcat - Tomat:通过 JMX 启动/停止/重新加载应用程序?如何通过程序管理应用程序的启动/停止/重启?
- javascript - 以更简单的方式过去 5 分钟,javascript
- android-studio - Android Instant Apps 示例未提取 GitHub 存储库
- javascript - 用于在多行中匹配特定单词之后的单词的正则表达式
- regex - 如何使用通配符为 gmail 中的所有一次性地址创建搜索过滤器
- php - 警告:session_start():当标头已发送时无法启动会话
- powershell - 如何使用 PowerShell 根据每个文件中的特定内容重命名文件夹中的文件?
- r - 如何拆分列中的数据以在 R 中绘制箱形图
- angular - 在 Visual Studio 2019 中创建新的 Asp.Net Core 2.1 Angular 项目时无法选择单个用户帐户
- php - 如何使用 PHP 在 FPDF 中居中表格