In some other databases (such as DB2 or Oracle with ROWNUM ), I can omit the ORDER BY in the OVER() ranking article. For example:
ROW_NUMBER() OVER()
This is especially useful when used with ordered views, for example:
SELECT t.*, ROW_NUMBER() OVER() FROM ( SELECT ... ORDER BY ) t
How can this be emulated in SQL Server? I found people using this trick , but this is wrong, as it will behave non-deterministically with respect to the order from the view:
-- This order here ---------------------vvvvvvvv SELECT t.*, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) FROM ( SELECT TOP 100 PERCENT ... -- vvvvv ----redefines this order here ORDER BY ) t
Concrete example (as can be seen on SQLFiddle ):
SELECT v, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN FROM ( SELECT TOP 100 PERCENT 1 UNION ALL SELECT TOP 100 PERCENT 2 UNION ALL SELECT TOP 100 PERCENT 3 UNION ALL SELECT TOP 100 PERCENT 4
Also, I cannot reuse any expression from the view to reproduce the ORDER BY in my case, since the view may not be available because it can be provided by some external logic.
So how can I do this? Can I do this at all?
sql sql-server tsql window-functions ranking-functions
Lukas Eder Sep 23 '13 at 14:24 2013-09-23 14:24
source share