如何使用循环增加 WHERE 子句中的数值?

How can I increment the numerical value in my WHERE clause using a loop?

我目前正在使用下面的 UNION ALL 解决方法来计算每个 old_eps_tfq 回归斜率ticker 基于其相应的 rownum 值(参见 WHERE rownum < x)。我有兴趣知道 old_eps_tfq 是什么,当 rownum < 4 然后将 4 增加 1 找出当 rownum < 5old_eps_tfq 是什么,依此类推(有 ~20 rownum)

我可以使用 PL/pgSQL 吗?

SELECT * FROM(
    WITH regression_slope AS(
        SELECT
            ROW_NUMBER() OVER ( PARTITION BY ticker ORDER BY earnings_growths_ped) AS rownum,
            *
        FROM "ANALYTICS"."vEARNINGS_GROWTHS"
        --WHERE ticker = 'ACN' 
        ORDER BY ticker )   
    SELECT
        ticker,
        current_period_end_date,
        max(earnings_growths_ped) AS max_earnings_growths_ped, 
        --max(rownum) AS max_rownum, 
        round(regr_slope(old_eps_tfq, rownum)::numeric, 2) AS slope,
        round(regr_intercept(old_eps_tfq, rownum)::numeric, 2) AS y_intercept,
        round(regr_r2(old_eps_tfq, rownum)::numeric, 3) AS r_squared
    FROM regression_slope  
    WHERE rownum < 4
    GROUP BY ticker, current_period_end_date
    ORDER BY ticker asc ) q

UNION ALL 

SELECT * FROM(
    WITH regression_slope AS(
        SELECT
            ROW_NUMBER() OVER ( PARTITION BY ticker ORDER BY earnings_growths_ped) AS rownum,
            *
        FROM "ANALYTICS"."vEARNINGS_GROWTHS"
        --WHERE ticker = 'ACN' 
        ORDER BY ticker )   
    SELECT
        ticker,
        current_period_end_date,
        max(earnings_growths_ped) AS max_earnings_growths_ped, 
        --max(rownum) AS max_rownum, 
        round(regr_slope(old_eps_tfq, rownum)::numeric, 2) AS slope,
        round(regr_intercept(old_eps_tfq, rownum)::numeric, 2) AS y_intercept,
        round(regr_r2(old_eps_tfq, rownum)::numeric, 3) AS r_squared
    FROM regression_slope  
    WHERE rownum < 5
    GROUP BY ticker, current_period_end_date
    ORDER BY ticker asc ) q

Here is my table

热门查询 SELECT * FROM (...) q 听起来没用。 那么你可以试试这个:

WITH regression_slope AS(
    SELECT
        ROW_NUMBER() OVER ( PARTITION BY ticker ORDER BY earnings_growths_ped) AS rownum,
        *
    FROM "ANALYTICS"."vEARNINGS_GROWTHS"
    --WHERE ticker = 'ACN' 
    ORDER BY ticker )   
SELECT
    max,
    ticker,
    current_period_end_date,
    max(earnings_growths_ped) AS max_earnings_growths_ped, 
    --max(rownum) AS max_rownum, 
    round(regr_slope(old_eps_tfq, rownum)::numeric, 2) AS slope,
    round(regr_intercept(old_eps_tfq, rownum)::numeric, 2) AS y_intercept,
    round(regr_r2(old_eps_tfq, rownum)::numeric, 3) AS r_squared
FROM regression_slope
INNER JOIN generate_series(4, 24) AS max -- the range 4 to 24 can be adjusted to the need
   ON rownum < max
GROUP BY max, ticker, current_period_end_date
ORDER BY max asc, ticker asc