限制每个字段

时间:2016-06-20 10:33:54

标签: sql postgresql greatest-n-per-group

假设我们有这样一个sql查询,其中包含来自另一个表的连接数据。

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

到目前为止,我们必须为几个resort_id做几个查询 如何更改查询以便我们只有一个查询(WHERE resort_id in(612,333,111),每个resort_id的结果不超过30个项目?

2 个答案:

答案 0 :(得分:2)

使用var month = new Array(); month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April"; month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August"; month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December"; for(n =3;n< 24; n++){ console.log(month[(n-3)%12]+","+month[(n-2)%12]+","+month[(n-1)%12]+","+month[n%12]) }计算每ROW_NUMBER的行数。

resort_id

答案 1 :(得分:1)

您可以将CTEROW_NUMBER()PARTITION BY

一起使用
WITH Results_CTE AS
(
    SELECT 
    pr.num, pr.resort_id, p.src_mask,ROW_NUMBER() over ( PARTITION BY pr.resort_id ORDER BY num) As Row_number
FROM 
    rutraveler.rt_photo_resort AS pr
    JOIN rutraveler.rt_photo AS p ON pr.photo_id = p.id
WHERE   pr.resort_id IN (A,B,C) AND p.src_mask is not null   
)

SELECT *
FROM Results_CTE
WHERE Row_number <= 30