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

后端 未结 3 806
别跟我提以往
别跟我提以往 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:24

    Can do this as a min and a max select statement, union them together and group by to eliminate any duplicates that one row groups would provide

     select item_id, group_id
    from(
    (select max(item_id) as item_id, group_id from table group by group_id) a
     union all
    (select min(item_id) as item_id, group_id from table group by group_id) b) qry
    group by item_id,group_id
    

    Not the prettiest I'm sure, but it works. It's usually best to have some type of logic built in, not "I do not care which 2 are returned."

    (Edit - I put the groupID in the groupo by and not item_ID. Ha, silly mistake I'll blame on dyslexia. Corrected now)

提交回复
热议问题