sql:选择表中特定字段集重复的所有条目

gab6jxml  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(295)

我需要一个查询来选择所有行中的所有条目,其中一个特定的2列对是重复的。例如,如果我的table (id int, Project varchar, Version varchar, Deployer varchar, Date DateTime) ,我要获取其中存在重复项目/版本的所有行。我做过这个

SELECT *
FROM Deployments
GROUP BY Project, Version
HAVING count(*) > 1;

但这似乎只能让我得到每个项目/版本对的第一行。我想得到所有的行。
我如何做到这一点?

bd1hkmkf

bd1hkmkf1#

在联接分组数据的位置使用联接,以仅选择适合的行。
在我的情况下,有相同的项目编号和版本

SELECT *
FROM Deployments d INNER JOIN 
(SELECT Project, Version
FROM Deployments
GROUP BY Project, Version
HAVING count(*) > 1) dd ON dd.Project = d.Project AND dd.Version = d.Version;
csbfibhn

csbfibhn2#

使用exists逻辑是一种方法:

SELECT d1.*
FROM Deployments d1
WHERE EXISTS (SELECT 1 FROM Deployments d2
              WHERE d2.id <> d1.id AND
                    d1.Project = d2.Project AND d1.Version = d2.Version);

您当前使用聚合的查询处于关闭状态,因为它使用 SELECT *GROUP BY . 有效版本可能是:

SELECT d1.*
FROM Deployments d1
INNER JOIN
(
    SELECT Project, Version
    FROM Deployments
    GROUP BY Project, Version
    HAVING COUNT(*) > 1
) d2
    ON d1.Project = d2.Project AND
       d1.Version = d2.Version;
kd3sttzy

kd3sttzy3#

当然,窗口函数是一种简单的方法:

select d.*
from (select d.*, count(*) over (partition by project, version) as cnt
      from deployments d
     ) d
where cnt >= 2

相关问题