SQL如何限制BOTTOM x行(PostgreSQL)

时间:2009-07-15 13:29:16

标签: sql postgresql

我有一个类似的查询:

SELECT 
EXTRACT(WEEK FROM j.updated_at) as "week",  count(j.id)  
FROM  jobs    
WHERE  
EXTRACT(YEAR FROM j.updated_at)=2009   
GROUP BY EXTRACT(WEEK FROM j.updated_at)  
ORDER BY week

哪个工作正常,但我只想显示最后说12周,LIMIT 12工作,但只给我前12个,我需要订单是连续周订单(即不反转)用于图表目的...

Postgresql中是否有等效语句,例如Show BOTTOM x items?

3 个答案:

答案 0 :(得分:7)

SELECT  *
FROM    (
        SELECT  EXTRACT(WEEK FROM j.updated_at) as "week",  count(j.id)  
        FROM    jobs    
        WHERE   EXTRACT(YEAR FROM j.updated_at)=2009   
        GROUP BY
                EXTRACT(WEEK FROM j.updated_at)  
        ORDER BY week DESC
        LIMIT 12
        ) q
ORDER BY
        week ASC

请注意,如果您在updated_at上有索引,则可以稍微重写此查询,以便提高效率:

SELECT  week,
        (
        SELECT  COUNT(j.id)
        FROM    jobs
        WHERE   updated_at >= start_week
                AND updated_at < end_week
        ) 
FROM    (
        SELECT  week,
               '04.01.2009'::DATE - EXTRACT(DOW FROM '04.01.2009'::DATE)::INTEGER + week * 7
               '04.01.2009'::DATE - EXTRACT(DOW FROM '04.01.2009'::DATE)::INTEGER + week * 7 + 7
        FROM   generate_series(42, 53) week
        ) q

答案 1 :(得分:3)

如果的值增加,您可以 ORDER BY WEEK DESC ,然后选择 TOP 12 ,对吗?

更新: 然后,您必须使用 ORDER BY Week ASC 重新排序12个结果行,使其按时间顺序排列。 (之后,我掩饰了将它们按升序排列的请求;谢谢你,etlerant!)

答案 2 :(得分:0)

SELECT * FROM 
(
    SELECT 
        EXTRACT(WEEK FROM j.updated_at) as "week",
        count(j.id)
    FROM
        jobs    
    WHERE  
        EXTRACT(YEAR FROM j.updated_at) = 2009
    GROUP BY EXTRACT(WEEK FROM j.updated_at)
    ORDER BY week desc limit 12
) as x
ORDER BY week asc;

“as x”很重要,因为from中的子查询需要别名。