Search code examples
sqldatabasedb2limit

DB2 - SQL- restrict result to only a few occurrences of a value in a certain column


So i have a job that selects some mobile notifications from a DB2 table. In order not to spam the users, i want to restrict the selection of too many of them. So my target is to select a maximum of 2 notifications per user.(The other ones will be selected on the next job run).

For example, if my table looks like this:

+-----------------+---------+-----------+
| Notification_ID | User_ID |   text    |
+-----------------+---------+-----------+
|               1 |       1 | blablabla |
|               2 |       1 | blablabla |
|               3 |       1 | blablabla |
|               4 |       1 | blablabla |
|               5 |       2 | blablabla |
|               6 |       2 | blablabla |
|               7 |       2 | blablabla |
|               8 |       3 | blablabla |
|               9 |       3 | blablabla |
|              10 |       4 | blablabla |
+-----------------+---------+-----------+

I need to get:

+-----------------+---------+-----------+
| Notification_ID | User_ID |   text    |
+-----------------+---------+-----------+
|               1 |       1 | blablabla |
|               2 |       1 | blablabla |
|               5 |       2 | blablabla |
|               6 |       2 | blablabla |
|               8 |       3 | blablabla |
|               9 |       3 | blablabla |
|              10 |       4 | blablabla |
+-----------------+---------+-----------+

Solution

  • You can do this using row_number():

    select n.*
    from (select n.*,
                 row_number() over (partition by user_id order by notification_id) as seqnum
          from notifications n
         ) n
    where seqnum <= 2;