我有一个订单表,我需要找到重复项 - 具有相同dd_number和dd_code的订单,但其中一个订单的状态必须为“checkout_completed”。
以下是我当前的SQL,它正确地找到了具有相同dd_number和dd_code的重复订单,但是我无法确定如何检查状态:
SELECT
tbOrders.id, tbOrders.dd_number, tbOrders.dd_code, tbOrders.status, COUNT(*) AS totalDupes
FROM
tbOrders
WHERE
dd_number IS NOT NULL
AND
dd_number != ''
AND
dd_number != '000000'
AND
dd_number != '00000000'
GROUP BY
dd_number, dd_code
HAVING totalDupes > 1
添加status ='checkout_complete'的WHERE子句不起作用,因为它要求两个命令具有相同的状态。任何帮助将不胜感激!
答案 0 :(得分:1)
SELECT
tbOrders.id, tbOrders.dd_number, tbOrders.dd_code, tbOrders.status, COUNT(*) AS totalDupes,
SUM(CASE WHEN status='checkout_complete' THEN 1 ELSE 0 END) as status_count
FROM
tbOrders
WHERE
dd_number IS NOT NULL
AND
dd_number != ''
AND
dd_number != '000000'
AND
dd_number != '00000000'
GROUP BY
dd_number, dd_code
HAVING totalDupes > 1 and status_count=1
您可以再引入一个状态为
的聚合字段统计记录答案 1 :(得分:1)
HAVING
子句:
HAVING totalDupes > 1
AND MAX(CASE WHEN status = 'checkout_complete' THEN 1 ELSE 0 END) = 1
虽然您的查询似乎有误。如果ID
是唯一的,则会选择随机ID
,同样适用于STATUS
。所有列都应该在GROUP BY
中,或者用聚合函数包装。请注意,只有MySQL旧版本接受您的语法。在任何其他RDBMS中,这将引发错误。