在一列中搜索重复的行,如何在另一列中重复排除?

时间:2016-08-22 16:19:38

标签: mysql

我正在搜索重复的地址但是我有一些结果,其中包含重复的结果"已完成"。如何排除显示的结果?这是我当前的查询

SELECT WorkOrder, list.Address, list.Completed
FROM list
INNER JOIN(
    SELECT list.Address
    FROM list
    WHERE list.Reference = 0
    GROUP BY Address
    Having COUNT(WorkOrder) = 2
    )
    temp ON list.Address = temp.Address
WHERE list.Address != ""
ORDER BY list.Address ASC, list.Completed ASC

示例输出:

WorkOrder | Address | Completed
41471286 | 127 LONG LN | 1
65381835 | 127 LONG LN | 1
39796565 | 13516 MOORING DR | 0
68128218 | 13516 MOORING DR | 1
39796559 | 13520 MOORING DR | 0
68004427 | 13520 MOORING DR | 1

我需要前两个结果才会出现在我的搜索中,因为两个结果都已标记为1。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT WorkOrder, Address, MIN(Completed) FROM list GROUP BY WorkOrder, Address

答案 1 :(得分:0)

您当前的方法并不遥远。在下面的查询中,我按 AddressCompleted列进行分组,使用以下条件确定是否保留地址/已完成对:

HAVING SUM(Completed) < 2

此条件将删除您的重复项,其中两个记录都已标记为完成,但将保留其他所有内容。

SELECT t1.WorkOrder,
       t1.Address,
       t1.Completed
FROM list t1
INNER JOIN
(
    SELECT Address, Completed
    FROM list
    WHERE Reference = 0             -- don't know what this is for, as it does not appear
    GROUP BY Address, Completed     -- in your sample data
    HAVING SUM(Completed) < 2       -- retain if completed is not marked twice or more
) t2
    ON t1.Address = t2.Address AND
       t1.Completed = t2.Completed
WHERE t1.Address != ""
ORDER BY t1.Address,
         t1.Completed