Reputation: 2728
My MySQL table has below records,
ID Name Account
-----------------------------------------
1 ABC PQR
2 DEF PQR
3 ABC PQR
4 XYZ ABC
5 DEF PQR
6 DEF ABC
I am looking for an output like
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
Here i mean that each duplicate should have a Sr Number or number the duplicates.
Name : ABC and Account : PQR when repeated in the table, there is an increment in the Duplicate Sr No from 1 to 2
Upvotes: 1
Views: 1887
Reputation: 8816
Try:
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;
Output :
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
Upvotes: 3
Reputation: 263733
MySQL doesn't yet support Window Function
like any other RDBMS
. This behaviour is similar with ROW_NUMBER()
which gives rank number for every record in a group. In mysql, this can be simulated by using user variables.
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
OUTPUT
╔════╦══════╦═════════╦════════════════╗
║ 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 ║
╚════╩══════╩═════════╩════════════════╝
Upvotes: 2