Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: WHERE clause in OVER(PARTITION BY... ORDER BY...)

I have the following query

;WITH tmp AS
(
    SELECT *, ROW_NUMBER()
    OVER
        (PARTITION BY to_tel, duration, call_date 
        ORDER BY rates_start DESC) as rn
    FROM ##TempTable
)
SELECT *
FROM tmp
WHERE rn = 1
ORDER BY customer_id, to_code, duration

But I would like to modify it where it doesn't give me the maximum rates_start, but the maximum rates_start before a certain date. Is there any way I can do this?

like image 625
S L Avatar asked Dec 14 '13 21:12

S L


People also ask

Can I use WHERE clause in partition by?

Thanks much. bhushan - we cannot use a where clause after the partition by is over.

Does the order of the WHERE clause in SQL matter?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.

Does partition by require ORDER BY?

The PARTITION BY and ORDER BY clause used in the call to FIRST_VALUE have an effect on that particular analytic function, but do not by themselves affect the final order of the result set. In general, if you want to order a result set in SQL, you need to use an ORDER BY clause.


Video Answer


1 Answers

You can add WHERE inside the cte part. I'm not sure if you still want to partition by call_date in this case (I removed it). Change the PARTITION BY part if needed.

;WITH tmp AS
(
    SELECT *, ROW_NUMBER()
    OVER
        (PARTITION BY to_tel, duration
        ORDER BY rates_start DESC) as rn
    FROM ##TempTable
    WHERE call_date < @somedate
)
SELECT *
FROM tmp
WHERE rn = 1
ORDER BY customer_id, to_code, duration
like image 196
Szymon Avatar answered Nov 15 '22 22:11

Szymon