mysql limit rows returned for each group -
i have result in 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 can select limited set of rows each group long number limit same dont know how this.
so want this:
1.select rows have group_id=1
2.select first 2 rows have group_id=2
3.select first row have group_id=3 , group_id=4
any pointers possibly if can done in single query
you can using variables:
select adm_no, code, value, group_id ( 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)) rn mytable cross join (select @rn:=0, @gr:=0) vars order group_id, code ) t (group_id = 1) or (group_id = 2 , rn <= 2) or (group_id in (3,4) , rn = 1)
variables @rn
, @gr
used implement row_number() on (partition ..)
window function available in other rdbmss sql server, postgresql, etc...
so, @rn
used enumerate records within each group_id
slice. using variable in outer query can expected result set.
please note use of nested conditionals, in order consume , then set @gr
variable.
Comments
Post a Comment