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?
Thanks much. bhushan - we cannot use a where clause after the partition by is over.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With