I found a bunch of questions on this topic with nice solutions but none of them actually deal with what to do if the data is not to be ordered in one specific way. For instance, the following query:
WITH MyCte AS ( select employee_id, RowNum = row_number() OVER ( order by employee_id ) from V_EMPLOYEE ORDER BY Employee_ID ) SELECT employee_id FROM MyCte WHERE RowNum > 0
works well if the data is to be ordered by employee_id. But what if my data does not have any specific order but the row numbers themselves act as an ID? My goal is to write a query like this (with the Row_Number()
function having no ORDER BY
clause):
WITH MyCte AS ( select employee_id, RowNum = row_number() OVER ( <PRESERVE ORIGINAL ORDER FROM DB> ) from V_EMPLOYEE ORDER BY Employee_ID ) SELECT employee_id FROM MyCte WHERE RowNum > 0
EDIT: Upon Googling, I figured out that this is not really possible. Can some suggest a workaround for this?
The row_number() window function can be used without order by in over to arbitrarily assign a unique value to each row.
Normally you can use ROW_NUMBER() as in the example below along with ORDER BY. If you try to use the ROW_NUMBER() function without ORDER BY clause, you will get an error as seen below. The function 'ROW_NUMBER' must have an OVER clause with ORDER BY .
The ROW_NUMBER function cannot currently be used in a WHERE clause. Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery.
The function 'ROW_NUMBER' must have an OVER clause with ORDER BY. The ORDER BY clause determines the sequence in which the rows are assigned their unique ROW_NUMBER within a specified partition. It is required.” So apparently the window order clause is mandatory for the ROW_NUMBER function in SQL Server.
Just in case it is useful to someone else. I just figured it out from elsewhere:
WITH MyCte AS ( select employee_id, RowNum = row_number() OVER (ORDER BY (SELECT 0)) from V_EMPLOYEE ORDER BY Employee_ID ) SELECT employee_id FROM MyCte WHERE RowNum > 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With