简体   繁体   中英

Joining on Row_Number() in SQL Server 2008

I'm trying to join a CTE on itself by using row_number() .

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.

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() ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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