可以像 - row_number()函数一样交叉加入窗口函数

时间:2015-03-13 06:34:27

标签: sql-server

窗口函数不能在where子句中使用。在下面的查询中,rn列只能在外部查询中使用where子句,如 -

select * from (
select *, row_number() over (partition by col1 order by col1) as rn 
from tab1) as abc
where rn = 1

我们可以使用rn列和交叉连接之类的东西 -

select *, row_number() over (partition by col1 order by col1) as rn 
from tab1 as a
cross join(select rn from a)

Just curious to know as i am trying to learn SQL server

1 个答案:

答案 0 :(得分:2)

你不能这样做。您必须在子查询中重复ROW_NUMBER()

SELECT *, ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col1) AS rn 
FROM tab1 AS a
CROSS JOIN (SELECT ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col1) AS rn FROM tab1) t

或者,使用公用表表达式

;WITH a AS (
   SELECT *, ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col1) AS rn 
   FROM tab1
)
SELECT *
FROM a
CROSS JOIN (SELECT rn FROM a) t