holden321 holden321 - 5 months ago 17
SQL Question

Limit per some field

Suppose we have such an sql query, with joined data from another table.

SELECT
pr.num, pr.resort_id, p.src_mask
FROM
rutraveler.rt_photo_resort AS pr
JOIN rutraveler.rt_photo AS p ON pr.photo_id = p.id
WHERE pr.resort_id = '612' AND p.src_mask is not null
ORDER BY num
LIMIT 30


So far we have to do several queries for several resort_id.

How to change the query so that we have only one query (WHERE resort_id in (612, 333, 111) with result no more than 30 items per each resort_id?

Answer

Use ROW_NUMBER to count the rows per resort_id.

SELECT resort_id, num, resort_id, src_mask 
FROM
(
  SELECT 
    pr.resort_id, pr.num, pr.resort_id, p.src_mask,
    ROW_NUMBER() OVER (PARTITION BY pr.resort_id ORDER BY num) AS rn
  FROM 
    rutraveler.rt_photo_resort AS pr
    JOIN rutraveler.rt_photo AS p ON pr.photo_id = p.id
  WHERE resort_id in (612, 333, 111) AND p.src_mask is not null
) data
WHERE rn <= 30
ORDER BY resort_id, num;
Comments