开发者

MySQL - group rows in 4's

开发者 https://www.devze.com 2023-01-09 05:08 出处:网络
I hav开发者_如何转开发e a product table like this: Product name , Affiliate ID , ProductCode a, 1, 1

I hav开发者_如何转开发e a product table like this:

Product name , Affiliate ID , ProductCode
a, 1, 1
b, 1, 2
c, 1, 3
d, 1, 5
e, 1, 7
f, 2, 4
g, 2, 6

I want to return first four products from each Affiliate ID. The 'ProductCode' column signifies the order in which the products were added, so can I use this column to sort my results. But I don't know how to return the first four results from each Affiliate ID? If I use the 'group' function it returns only one row of each affiliate ID.


Look to the example in this link:

Within-group quotas (Top N per group)

it is exactly that you need.

 SELECT AffiliateId, ProductCode 
 FROM ( 
    SELECT 
      AffiliateId, ProductCode, 
      IF( @prev <> ID  @rownum := 1, @rownum := @rownum+1 ) AS rank, 
      @prev := ID 
    FROM your table 
 JOIN (SELECT @rownum := NULL, @prev := 0) AS r 
 ORDER BY AffiliateId, ProductCode 
 ) AS tmp 
 WHERE tmp.rank <= 4
 ORDER BY AffiliateId, ProductCode; 
0

精彩评论

暂无评论...
验证码 换一张
取 消