I have a below table in sql server 2014
Empno Resign Hour Dept
1000 2999-01-01 40 20
1000 2999-01-01 40 21
1001 2999-01-01 40 22
1001 2999-01-01 40 23
I need to pick a top record based on Resignation date and Hour. It doesn't matter row with which dept gets picked up. So I went with query
SELECT *
FROM(
SELECT Empno,Resign, Hour, Dept,
ROW_NUMBER() OVER(PARTITION BY Empno ORDER BY Resign DESC,
hour DESC) AS Row
FROM Table ) AS master
WHERE master.Row = 1
AND master.Empno = '1000';
I got back with
EmployeeNumber ResignationDate Hour Dept Row
1000 2999-01-01 40 20 1
I understand sql server doesn't guarantee the order(in this case row with which dept) of the row number unless an order by clause is specified for the Dept.
I dont mind which row with which dept gets picked up but would this happen consistently to pick one, based on some index or id, how would the top would be produced by the query plan?
In the row_number I can simply add another orderby based on dept so that it consistently picks up one but I dont want to do that.
No. You have to add order by
with unique combination to force non-arbitrary output.
And why? Its easy question - sql server don't see tables as human. He reads and finds pages which not may not be near or in a row.
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.