1

I'm trying to select below table, grouped by two (=max, if there is only one, show one) of each supplier_id. But, after all suppliers are selected it needs to start over. So this is the table:

Table: products
ID Supplier_id Name created_at
---------------------------------------------
1 1 productname 2014年01月12日
2 3 productname 2014年01月12日
3 2 productname 2014年01月18日
4 2 productname 2014年01月18日
5 3 productname 2014年01月17日
6 1 productname 2014年01月17日
7 2 productname 2014年01月16日
8 4 productname 2014年01月10日
9 4 productname 2014年01月14日
10 2 productname 2014年01月17日
11 5 productname 2014年01月13日

After selecting the rows I want this result:

Table: products
ID Supplier_id Name created_at
----------------------------------------------
1 1 productname 2014年01月12日
6 1 productname 2014年01月17日
3 2 productname 2014年01月18日
4 2 productname 2014年01月18日
2 3 productname 2014年01月12日
5 3 productname 2014年01月17日
8 4 productname 2014年01月10日 
9 4 productname 2014年01月14日
11 5 productname 2014年01月13日
7 2 productname 2014年01月16日
10 2 productname 2014年01月17日

On https://stackoverflow.com/questions/15969614/in-sql-how-to-select-the-top-2-rows-for-each-group I almost found what I was looking for.

SELECT *
FROM products as p
WHERE 
 (
 SELECT COUNT(*) 
 FROM products as pr
 WHERE p.supplier_id = pr.supplier_id AND p.created_at >= pr.created_at
 ) <= 2
 order by p.supplier_id

But as I told, after 2 of each supplier_id's are selected it needs to start over if there are any rows left. Anyone who knows this is possible with a query?

asked Jan 29, 2015 at 9:58

1 Answer 1

2

I think you need something using ROW_NUMBER() and (integer) division by 2, along the lines of this:

WITH p AS
( SELECT *, ROW_NUMBER() OVER (PARTITION BY supplier_id ORDER BY id)-1 AS rn
 FROM products
)
SELECT * 
FROM p
ORDER BY rn/2, supplier_id, rn ;

Tested at SQLFiddle.

answered Jan 29, 2015 at 12:12
1
  • Very nice!! Thank you, it works like a charm! Commented Jan 29, 2015 at 12:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.