DB2 SQL - Limit the number of groups returned

tbcrawford :

I am trying to find a way to limit the first n groups returned. I have a scenario where I want to only select 10 groups of user data and no more. How would I limit 10 groups of user data where the group size for the user can vary. Some groups may have more than 4 records for a user, some may have less than 4 records for a user. But I only want to get 10 users at a time. I tried thinking about how ROW_NUMBER() and PARTITION BY could be leveraged or even FETCH FIRST N ROWS ONLY could be leveraged, but couldn't come up with a solution.

Below is some sample data. NOTE: The GROUP_NUMBER column doesn't exist in the data set I am working with. It is what I was thinking about creating via SQL so that I can leverage this to select where the "GROUP_NUMBER" < 11 for example. I am absolutely open to other solutions given my question, but this was one solution I was thinking about but didn't know how to do it.

+-----------+--------------+-----------+-----------+----------+------------------+--------------+
| REQUESTID |    USERID    | COMPANYID | FIRSTNAME | LASTNAME |      EMAIL       | GROUP_NUMBER |
+-----------+--------------+-----------+-----------+----------+------------------+--------------+
|       157 | test.bulkup1 |        44 | BulkUp    | Test     | [email protected] |            1 |
|       157 | test.bulkup1 |        44 | BulkUp    | Test     | [email protected] |            1 |
|       157 | test.bulkup1 |        44 | BulkUp    | Test     | [email protected] |            1 |
|       162 | test.bulkup2 |        44 | BulkUp    | Test     | [email protected] |            2 |
|       162 | test.bulkup2 |        44 | BulkUp    | Test     | [email protected] |            2 |
|       162 | test.bulkup2 |        44 | BulkUp    | Test     | [email protected] |            2 |
|       162 | test.bulkup2 |        44 | BulkUp    | Test     | [email protected] |            2 |
|       187 | test.bulkup3 |        44 | BulkUp    | Test     | [email protected] |            3 |
|       187 | test.bulkup3 |        44 | BulkUp    | Test     | [email protected] |            3 |
|       187 | test.bulkup3 |        44 | BulkUp    | Test     | [email protected] |            3 |
|       187 | test.bulkup3 |        44 | BulkUp    | Test     | [email protected] |            3 |
|       192 | test.bulkup4 |        44 | BulkUp    | Test     | [email protected] |            4 |
+-----------+--------------+-----------+-----------+----------+------------------+--------------+
Gordon Linoff :

You can use dense_rank(). I think you want:

select t.*
from (select t.*,
             dense_rank() over (order by requestId) as seqnum
      from t
     ) t
where seqnum <= 3;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390744&siteId=1