sql—根据组中是否存在值从重复项中选择两个记录

vtwuwzda  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(319)

我有一个表,其中一列中有重复项。我需要保留其中一个重复记录并删除另一个。但是在我删除一个之前,我必须将所有其他与要删除的表相关的表记录指向我要保留的记录。另外,如果可能的话,我想检查一个条件来选择一个保留和删除,如果这个条件不满足,那么保留 MIN() 并删除 MAX() .
例如,我有一个名为workers的表

我想按workerid列分组,然后检查组中是否有2条记录有 isActive = 'No' . 如果是这样,抓取该记录的工作者并将其标记为tokeep。如果组中的两个记录的isactive都为yes,则 MIN(worker) 作为保留和 MAX(worker) 作为托德莱特。
所以,基于这个例子的结果是这样的

有没有可能编写一个查询来实现这一点?我试着写下面的两个查询,但两次都得到了错误的结果。只有10003出现在两个结果中。

Select max(woWorker.pk) as  ToKeep, min(woWorker.Pk) as ToDelete
from woWorker 
group by woWorker.fkosCompanyWorker, woWorker.isActive
having (case when isActive = 'No' then 1 else 0 end) = 1

Select ToDelete = case when t.ToDelete is not null then t.ToDelete
                      else workers.worker end
from 
(Select Workers.worker as ToDelete, workerID
from Workers 
group by Workers.workerID, Workers.isActive, Workers.worker
having (case when isActive = 'No' then 1 else 0 end) = 1) t
join workers on t.workerID = workers.workerID
group by workers.workerID, t.ToDelete, workers.worker
yiytaume

yiytaume1#

你可以在这里使用旋转逻辑。

SELECT
    workerID,
    CASE WHEN MIN(isActive) <> MAX(isActive)
         THEN MAX(CASE WHEN isActive = 'Yes' THEN worker END)
         ELSE MIN(worker) END AS ToKeep,
    CASE WHEN MIN(isActive) <> MAX(isActive)
         THEN MAX(CASE WHEN isActive = 'No' THEN worker END)
         ELSE MAX(worker) END AS ToDelete
FROM Workers
GROUP BY
    workerID;

演示

但是,如果您只想查看要保留的记录,那么 ROW_NUMBER 提供了一种简单的方法:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY workerID ORDER BY isActive DESC, worker) rn
    FROM Workers
)

SELECT worker, workerID, isActive
FROM cte
WHERE rn = 1;

演示

相关问题