← Back to context

Comment by SPBS

4 years ago

This only targets SELECT queries right? I guess there's not much to improve on for INSERT, UPDATE and DELETE queries.

BTW window definitions are reusable using the WINDOW clause, there's no need to define it over and over in SELECT.

    SELECT
        date,
        CASE WHEN is_valid_price
            THEN price_adjusted / LAG(price_adjusted, 1) OVER w - 1 + dividend_return
            ELSE NULL
        END AS return_total,
        CASE WHEN is_valid_price
            THEN price_adjusted_usd / LAG(price_adjusted_usd, 1) OVER w - 1 + dividend_return
            ELSE NULL
        END AS return_usd,
        CASE WHEN is_valid_price
            THEN price_adjusted / LAG(price_adjusted, 1) OVER w - 1 + dividend_return - interest_rate / 252
            ELSE NULL
        END AS return_excess,
        CASE WHEN is_valid_price
            THEN price_adjusted_usd / LAG(price_adjusted_usd, 1) OVER w - 1 + dividend_return - interest_rate / 252
            ELSE NULL
        END AS return_usd_excess
    FROM
        prices
    WINDOW
        w AS (PARTITION BY sec_id ORDER BY date)
    ;