T-SQL:OVER中的WHERE子句(PARTITION BY ... ORDER BY ...)

时间:2013-12-14 21:47:51

标签: sql-server tsql

我有以下查询

;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

但是我想修改它,它不会给我最大的rates_start,但是在特定日期之前的最大rate_start。我有什么方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:16)

您可以在cte部分中添加WHERE。在这种情况下,我不确定您是否仍希望按call_date进行分区(我将其删除)。如果需要,请更改PARTITION BY部分。

;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