Query picking randomly when using rownumber()

ASHMITP 141 Reputation points
2022-11-08T02:33:20.9+00:00

Hi All,

Here is my sample script :

TMP1 have 2 rows with identical values of the field used by Partition , thus TMP2 is picking randomly when doing RN=1.
Can this be fix ?

258027-image.png

WITH TMP1 AS (
SELECT
distinct [HERO ID],
[Service Unit Name],
[Location Facility ID],
[Health Service],
Department,
,Division, Specialty,
[Effective To],
[Effective from],
[Secure Org Flag],
, ISNULL([Service Unit Hierarchy],99) AS [Service Unit Hierarchy]
FROM VIEWMAPPING
), TMP2 AS (
SELECT *, RN=ROW_NUMBER() OVER(PARTITION BY [HERO ID] ORDER BY [Service Unit Hierarchy] ASC, [Effective To] Desc, [Effective From] Desc, [Location Facility ID] ) FROM TMP1
)
SELECT [HERO ID],
[Service Unit Name],
[Location Facility ID],
Department,
Division, Specialty,
[Effective To],
[Effective from],
[Secure Org Flag]
FROM TMP2 WHERE RN=1

Thanks

Developer technologies Transact-SQL
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2022-11-08T06:16:46.593+00:00

    thus TMP2 is picking randomly when doing RN=1.

    Randomly in which way? By your screenshot the resultset have two identical rows, so how can one say it's "randomly"; you get always the same.

    Please post table design as DDL, some sample data as DML statement and the expected result.

    0 comments No comments

  2. NikoXu-msft 1,916 Reputation points
    2022-11-08T06:34:19.197+00:00

    Hi @ASHMITP ,

    Role of PARTITION BY:
    Divides the result set produced by the FROM clause into partitions to which the ROW_NUMBER function is applied.
    If PARTITION BY is not specified, the function treats all rows of the query result set as a single group.
    It would be a good idea for you to post your table structure and your expected output so we can understand your needs.

    Best regards
    Niko

    0 comments No comments

  3. Tom Phillips 17,771 Reputation points
    2022-11-09T15:14:01.027+00:00

    Your order is not distinct. This results in "randomly" picking a row.

    You need to change this to a sort which returns the same row every time.

    ORDER BY [Service Unit Hierarchy] ASC, [Effective To] Desc, [Effective From] Desc, [Location Facility ID]   
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.