根据订单的准确程度,您可以执行以下操作。
这是获取带有计数的所有唯一控件/代码/数量,以获取一个标志以了解这是否是重复行,并按控件/代码/数量排序,以便它们按顺序排列。它进行交叉连接以初始化一些用户变量。
然后它计算一个计数器,只有在任何控制/代码/数量发生变化并且它是重复行时才增加它。然后设置用户变量来存储之前的控制/代码/数量值。
然后,外部查询将结果重新排序为 id 顺序。
SELECT sub3.id,
sub3.control,
sub3.code,
sub3.amount,
sub3.dup_id
FROM
(
SELECT sub2.id,
sub2.control,
sub2.code,
sub2.amount,
@cnt:=IF(@control=control AND @code=code AND @amount=amount AND sub2.id_count IS NOT NULL, @cnt, IF(sub2.id_count IS NULL, @cnt, @cnt + 1)),
@control:=control,
@code:=code,
@amount:=amount,
IF(sub2.id_count IS NULL, NULL, @cnt) AS dup_id
FROM
(
SELECT mwt.id, mwt.control, mwt.code, mwt.amount, sub1.id_count
FROM mwt
LEFT OUTER JOIN
(
SELECT control, code, amount, COUNT(id) AS id_count
FROM mwt
GROUP BY control,code,amount
HAVING id_count > 1
) sub1
ON mwt.control = sub1.control
AND mwt.code = sub1.code
AND mwt.amount = sub1.amount
ORDER BY mwt.control, mwt.code, mwt.amount
) sub2
CROSS JOIN
(
SELECT @cnt:=0, @control:=0, @code:=0, @amount:=0
) sub0
) sub3
ORDER BY id
请注意,这是按控件、代码和数量排序的,因此与您所需的输出不完全匹配(这需要首先获取按 id 排序的第一个重复项)。
编辑 - 更简单更好的方法。这将获取所有具有最小 id 的重复行(按最小 id 排序),并使用用户变量为这些行添加序列号。然后 LEFT OUTER JOIN 将其返回到主表,以将该序列号放入所有匹配的行中。
SELECT mwt.id, mwt.control, mwt.code, mwt.amount, sub2.dup_id
FROM mwt
LEFT OUTER JOIN
(
SELECT sub1.id, sub1.control, sub1.code, sub1.amount, @cnt:=@cnt+1 AS dup_id
FROM
(
SELECT MIN(id) AS id, control, code, amount
FROM mwt
GROUP BY control,code,amount
HAVING COUNT(id) > 1
ORDER BY id
) sub1
CROSS JOIN
(
SELECT @cnt:=0
) sub0
) sub2
ON mwt.control = sub2.control
AND mwt.code = sub2.code
AND mwt.amount = sub2.amount
ORDER BY mwt.id