I have a table with products from shops. These products have a valid_from and valid_to date. In my query, I want to have only the first x records of each shop which are currently valid, ordered by last insert desc.
I am currently using the following query:
SELECT * FROM
(
SELECT
s.id as shopid, ss.name as shopname, p.name as productname, p.validfrom, p.validto
FROM
product p
JOIN
shop s ON p.shopid = s.id
WHERE
s.status = 'Active' AND
(now() BETWEEN p.validfrom and p.validto)
ORDER BY p.insert DESC
) as a
GROUP BY
shopid
ORDER BY
shopname asc
This obviously only gives me the latest record of each shop, but I want to have latest 2 or 3 records. How can I achieve this?
Bonus question: I want to differ per shop. So for shop A I'd like to have only the first record and for shop B the first two records. You may assume I have some database field for each shop that holds this number, like s.num_of_records.
The similar issue (possible duplicate) got me in the right direction, but it not completely solve my problem (see latest comment)