Search code examples
mysqlsqlfreeradius

MySQL find duplicates + one other field


I'm working with a freeradius server with MySQL backend and I am trying to select the logged in users from the radacct table. The table looks like:

╔══════════╦═══════════════╦═════════════════════╦═════════════════════╗
║ USERNAME ║ ACCTSESSIONID ║    ACCTSTARTTIME    ║    ACCTSTOPTIME     ║
╠══════════╬═══════════════╬═════════════════════╬═════════════════════╣
║ test2    ║ 00000051      ║ 2013-09-06 15:44:05 ║ 2013-09-06 15:44:26 ║
║ jason    ║ 00000057      ║ 2013-09-06 15:44:56 ║ 2013-09-06 15:46:08 ║
║ jason    ║ 00000058      ║ 2013-09-06 15:44:56 ║ 2013-09-06 15:46:08 ║
║ test1    ║ 00000059      ║ 2013-09-06 15:44:57 ║ 2013-09-06 15:46:08 ║
║ test1    ║ 0000005A      ║ 2013-09-06 15:44:57 ║ 2013-09-06 15:46:08 ║
║ test2    ║ 0000005B      ║ 2013-09-06 15:44:57 ║ 2013-09-06 15:46:08 ║
║ jason    ║ 00000061      ║ 2013-09-06 15:46:39 ║ NULL                ║
║ jason    ║ 00000062      ║ 2013-09-06 15:46:39 ║ NULL                ║
║ test1    ║ 00000063      ║ 2013-09-06 15:46:39 ║ NULL                ║
║ test1    ║ 00000064      ║ 2013-09-06 15:46:39 ║ NULL                ║
║ test2    ║ 00000065      ║ 2013-09-06 15:46:39 ║ NULL                ║
╚══════════╩═══════════════╩═════════════════════╩═════════════════════╝

Each line is a log in session, the lines where 'acctstoptime' is null are considered to be active. I am trying to get the username and acctsessionid for each username that has more than 1 row with a null acctstoptime.


Solution

  • Here's one way to get the specified result:

    SELECT s.username
         , s.acctsessionid
      FROM (
             SELECT r.username
               FROM radacct r 
              WHERE r.acctstoptime IS NULL
              GROUP BY r.username
             HAVING COUNT(1) > 1
           ) d
      JOIN radacct s
        ON s.username = d.username
     WHERE s.acctstoptime IS NULL
     ORDER
        BY s.username
         , s.acctsessionid