简体   繁体   中英

mysql limit rows returned for each group

i have this result in a table

+------------------------------------------------+
|adm_no   |   code     | value   |   group_id    |
+------------------------------------------------+
|1200     |  101       | 50      |    1          |
+------------------------------------------------+
|1200     |   102      | 60      |    1          |
+------------------------------------------------+
|1200     |  121       | 62      |    1          |
+------------------------------------------------+
|1200     |  233       |  50     |   2           |
+------------------------------------------------+
|1200     |  231       |  98     |   2           |
+------------------------------------------------+
|1200     |  232       | 85      |    2          |
+------------------------------------------------+
|1200     | 511        |   75    |     3         |
+------------------------------------------------+
|1200     |  585       |   38    |     3         |
+------------------------------------------------+
|1200     |  711       |    45   |      4        |
+------------------------------------------------+
|1200     |   785      |     45  |      4        |
+------------------------------------------------+ 

now i can select a limited set of rows for each group as long as the number to limit is the same but i dont know how to do this.

so what i want to do is this:

1.select all rows that have group_id=1

2.select only the first two rows that have group_id=2

3.select only the first row that have group_id=3 and group_id=4

any pointers possibly if it can be done in a single query

You can do it using variables:

SELECT adm_no, code, value, group_id
FROM (
  SELECT adm_no, code, value, group_id,
         @rn := IF (@gr = group_id,
                    IF(@gr := group_id, @rn+1, @rn+1),
                    IF(@gr := group_id, 1, 1)) AS rn
  FROM mytable
  CROSS JOIN (SELECT @rn:=0, @gr:=0) AS vars
  ORDER BY group_id, code ) t
WHERE (group_id = 1) 
      OR (group_id = 2 AND rn <= 2) 
      OR (group_id IN (3,4) AND rn = 1) 

Variables @rn , @gr are used to implement ROW_NUMBER() OVER (PARTITION BY ..) window function available in other RDBMSs like SQL SERVER, PostgreSQL, etc...

So, @rn essentially is used to enumerate records within each group_id slice. Using this variable in an outer query we can easily get the expected result set.

Please note the use of nested conditionals , in order to properly consume and then set @gr variable.

Demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM