SQL - Restrict the number of rows returned based on a count of rows

后端 未结 3 835
别跟我提以往
别跟我提以往 2021-01-13 06:04

Here is what my data looks like:

item_ID | group_ID | count_of_items_in_group

2|ABC|3

5|ABC|3

9|ABC|3

29|DEF|3

3|DEF|3

4|DEF|3

200|XYZ|2

300|XYZ|2

6         


        
3条回答
  •  滥情空心
    2021-01-13 06:15

    Use the ROW_NUMBER() function for this:

    SELECT *
    FROM (select *,ROW_NUMBER() OVER (PARTITION BY group_id ORDER BY item_id) as RowRank 
          from items_in_groups
          )sub
    WHERE RowRank <=2
    

    Demo: SQL Fiddle

    The ROW_NUMBER() function assigns a number to each row. PARTITION BY is optional, but used to start the numbering over for each value in that group, ie: if you PARTITION BY group_id then for each unique group_id value the numbering would start over at 1. ORDER BY of course is used to define how the counting should go, and is required in the ROW_NUMBER() function.

提交回复
热议问题