我有一个SQL查询,可以进行一些排名,如下所示:
SELECT RANK() OVER(PARTITION BY XXX ORDER BY yyy,zzz,oooo) as ranking, *
FROM SomeTable
WHERE ranking = 1 --> this is not possible
我想在最后的WHERE条件中使用该排名。
现在我将此查询嵌套在另一个查询中并对那里的排名进行过滤,但是没有更简单或更快的方法从SELECT语句中过滤这些值吗?
答案 0 :(得分:7)
使用CTE(公用表表达式) - 仅为下一个语句排序“内联”视图:
;WITH MyCTE AS
(
SELECT
RANK() OVER(PARTITION BY XXX ORDER BY yyy,zzz,oooo) as ranking,
*
FROM SomeTable
)
SELECT *
FROM MyCTE
WHERE ranking = 1 --> this is now possible!
答案 1 :(得分:1)
select * from (
select RANK() OVER(PARTITION BY name ORDER BY id) as ranking, *
from PostTypes
) A
where A.ranking = 1
http://data.stackexchange.com/stackoverflow/query/edit/59515
答案 2 :(得分:0)
对于以前的帖子很抱歉,我忘了:窗口函数只能用于select或order by子句。 您将不得不使用子查询:
SELECT * FROM
(
SELECT RANK() OVER(PARTITION BY XXX ORDER BY yyy,zzz,oooo) as ranking, *
FROM SomeTable
) t
WHERE ranking = 1
或CTE。