Sql : Row numbers with partition limitations

Krish 81 Reputation points
2020-12-07T17:16:22.633+00:00

Hi Everyone,
Can I request you to clarify on the below confusion please with SQL server row_number with partition by clause?

Can we use the different table columns in the partition by clause while generating the row numbers ?

Ex : Select row_number() over (partition by table1.column1 , table2.column1 order by
Table2.column1)

From
Table1
Inner join table2 on table1.id=table2.id

This query is giving the wrong row numbers . Is there any limitation to not to use the multiple table columns in the partition by. In the above query table2.column1 is a date column which can have duplicates ..

Thank you.

Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

3 answers

Sort by: Most helpful
  1. Tom Phillips 17,771 Reputation points
    2020-12-07T18:15:44.447+00:00

    What do you mean by "wrong row numbers"?

    Since your join is not your partition clause, and you said table2.column1 has duplicates, you are likely getting a random row selected from table2 when there are duplicate rows with the same date.


  2. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2020-12-07T22:55:58.523+00:00

    Yes, there are no limitations on where the partitioning columns come from.

    Since we don't see your full query, we can't say exactly what is wrong. However, in your post, I notice this:

    over (partition by table1.column1 , table2.column1 order by

    Table2.column1)

    That is, you have the same column in the PARTITION BY clause as in the ORDER BY clause. This only makes sense if you want to state that you don't care about the order. (And in that case I prefer to say ORDER BY (SELECT 1) instead. The PARTITION BY clause states that every combo the row numbering should start at 1 and be ordered by the columns in the ORDER BY clause. But if you have a column from the PARTITION BY clause in ORDER BY, that column has the same value throughout the partitioning and does not contribute to ordering.

    0 comments No comments

  3. CathyJi-MSFT 22,396 Reputation points Microsoft External Staff
    2020-12-08T05:58:23.997+00:00

    Hi @kirankumar-3620,

    > Is there any limitation to not to use the multiple table columns in the partition by.

    No, it is supported. Could you share us your table structure and some sample data along with your expected result?

    Best regards,
    Cathy

    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.