2016-02-22 44 views
2

因此,我有一項工作可以從DB2表中選擇一些移動通知。 爲了不給用戶發送垃圾郵件,我想限制其中太多的選擇。所以我的目標是每個用戶最多選擇2個通知(其他人將在下一次作業中選擇)。DB2 - SQL-將結果限制在特定列中只有少數幾次出現

例如,如果我的表看起來像這樣:

+-----------------+---------+-----------+ 
| 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 | 
+-----------------+---------+-----------+ 

我需要得到:

+-----------------+---------+-----------+ 
| 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 | 
+-----------------+---------+-----------+ 

回答

2

可以使用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;