简体   繁体   English

加入SQL Server 2008中的Row_Number()

[英]Joining on Row_Number() in SQL Server 2008

I'm trying to join a CTE on itself by using row_number() . 我正在尝试使用row_number()加入CTE。

Using this syntax 使用此语法

select row_number() over(order by x.patientid, x.dischargedate) as rn
         ,* from x
    inner join x as x2 on row_number() over(order by x.patientid,    x.dischargedate)=row_number() over(order by x2.patientid, x2.dischargedate)

The CTE x does what I want it to but when I try to join on the row number I get the error Msg 4108, Level 15, State 1, Line 35 Windowed functions can only appear in the SELECT or ORDER BY clauses. CTE x做我想要的但是当我尝试连接行号时我得到错误Msg 4108, Level 15, State 1, Line 35 Windowed functions can only appear in the SELECT or ORDER BY clauses.

I know that I can include the row_number in the CTE itself and give it a column name and then join on something like x.rn but is there any logical reason I can't think of as to why you can't directly join on the function row_number() ? 我知道我可以在CTE本身中包含row_number并给它一个列名,然后加入像x.rn这样的x.rn但是有任何逻辑上的原因我无法想到为什么你不能直接加入function row_number()

In the join condition of an inner join you are performing a filter on the cartesian product of the two tables. 在内连接的连接条件中,您正在对两个表的笛卡尔积进行过滤。 Your operation row_number() over (order by xa, xb) would therefore not be an operation on table x but on the cartesian production. 因此,您的操作row_number()over(按xa,xb排序)将不是对表x的操作,而是对笛卡尔生产的操作。

If you would have it in the join condition, the system would just in the phase of determining the candidate rows of your select. 如果你想在连接条件下使用它,系统就会处于确定你选择的候选行的阶段。 You cannot have an operation that has its semantics defined only on the result rows in use for finding those result rows. 您不能拥有仅在用于查找结果行的结果行上定义其语义的操作。 The filter would change the result and the result would change the filter. 过滤器会更改结果,结果会更改过滤器。

The difference with the CTE is that you define your row_number column on an intermediate result set and then do the join. 与CTE的不同之处在于,您在中间结果集上定义了row_number列, 然后执行连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM