我的MySQL表有以下记录,
ID Name Account
-----------------------------------------
1 ABC PQR
2 DEF PQR
3 ABC PQR
4 XYZ ABC
5 DEF PQR
6 DEF ABC
我正在寻找像
这样的输出 ID Name Account Duplicate Sr No.
-----------------------------------------
1 ABC PQR 1
2 DEF PQR 1
3 ABC PQR 2
4 XYZ ABC 1
5 DEF PQR 2
6 DEF ABC 1
这里我的意思是每个副本都应该有一个Sr编号或重复数字。
名称:ABC和账户:PQR在表格中重复时,复制Sr No从1增加到2
答案 0 :(得分:3)
尝试:
SELECT t1.id, t1.name, t1.account
, (SELECT COUNT(*)
FROM tableName t2
WHERE t2.name = t1.name
AND t2.account = t1.account
AND t2.id <= t1.id) AS dupno
FROM tableName t1;
输出
ID NAME ACCOUNT DUPNO
-- ---- ------- -----
1 ABC PQR 1
2 DEF PQR 1
3 ABC PQR 2
4 XYZ ABC 1
5 DEF PQR 2
6 DEF ABC 1
答案 1 :(得分:2)
MySQL不像任何其他Window Function
一样支持RDBMS
。此行为与ROW_NUMBER()
类似,后者为组中的每条记录提供排名。在mysql中,可以使用用户变量来模拟它。
SELECT ID, Name, Account, DuplicateSR_No
FROM
(
select ID,
Name,
Account,
@sum := if(@nme = Name AND @acct = Account, @sum ,0) + 1 DuplicateSR_No,
@nme := Name,
@acct := Account
from TableName,
(select @nme := '', @sum := 0, @acct := '') vars
order by Name, Account
) s
ORDER BY ID
输出
╔════╦══════╦═════════╦════════════════╗
║ ID ║ NAME ║ ACCOUNT ║ DUPLICATESR_NO ║
╠════╬══════╬═════════╬════════════════╣
║ 1 ║ ABC ║ PQR ║ 1 ║
║ 2 ║ DEF ║ PQR ║ 1 ║
║ 3 ║ ABC ║ PQR ║ 2 ║
║ 4 ║ XYZ ║ ABC ║ 1 ║
║ 5 ║ DEF ║ PQR ║ 2 ║
║ 6 ║ DEF ║ ABC ║ 1 ║
╚════╩══════╩═════════╩════════════════╝