Arrange duplicates and number the records in a sequence - MySQL

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-28 06:14:36

问题


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


回答1:


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
  • SQLFiddle Demo

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 ║
╚════╩══════╩═════════╩════════════════╝



回答2:


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 


来源:https://stackoverflow.com/questions/15743696/arrange-duplicates-and-number-the-records-in-a-sequence-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!