1

我的 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 Number 或对副本进行编号。

Name : ABC and Account : PQR 当在表中重复时,Duplicate Sr No 从 1 增加到 2

4

2 回答 2

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 
于 2013-04-01T13:08:14.537 回答
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 ║
╚════╩══════╩═════════╩════════════════╝
于 2013-04-01T12:43:59.837 回答