how to fix an error : Windowed functions cannot be used in the context of another windowed function or aggregate.

Priyanka Awasare 20 Reputation points
2024-02-01T08:48:54.2366667+00:00

below is the query :

DECLARE @InputValue INT = 840;

SELECT
    @InputValue AS InputValue,
    SUM((CASE 
            WHEN @InputValue >= PRRangeUpto THEN (LEAD(PRRangeUpto, 1, @InputValue) OVER (ORDER BY PRRangeUpto) - PRRangeUpto) * PRRate
            ELSE 0
        END)) AS TotalAmount
FROM
    PRRateRange
WHERE
    @InputValue >= PRRangeUpto;


this query gives an error : Windowed functions cannot be used in the context of another windowed function .How to fix it?

SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,702 questions
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2024-02-01T09:01:02.3733333+00:00

    Try something like this:

    ;
    with Q as
    (
        select *, lead(PRRangeUpto, 1, @InputValue) over (order by PRRangeUpto) as ld
        from PRRateRange
    )
    select @InputValue AS InputValue, sum(case when @InputValue >= PRRangeUpto then ld * PRRate end) as TotalAmount
    from Q
    where @InputValue >= PRRangeUpto
    

    If it does not work, then show details to reproduce the problem.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.