简体   繁体   中英

How to get same rownumber() for same values

Need to get the same "Row Number" if the values gets repeated in Column Week and Desc. For the following table:

╔════════╦═══════╦
║  Week  ║ Desc  ║
╠════════╬═══════╬
║      1 ║  FF   ║
║      1 ║  ss   ║
║      1 ║  ss   ║
║      2 ║  FF   ║
║      2 ║  ss   ║
║      4 ║  FF   ║
║      4 ║  FF   ║
║      4 ║  ss   ║
║      4 ║  ss   ║
╚════════╩═══════╝

The expected result is:

╔════════╦═══════╦════════╗
║  Week  ║ Desc  ║ RowNum ║
╠════════╬═══════╬════════╬
║      1 ║  FF   ║    1   ║
║      1 ║  ss   ║    2   ║
║      1 ║  ss   ║    2   ║
║      2 ║  FF   ║    1   ║
║      2 ║  ss   ║    2   ║
║      4 ║  FF   ║    1   ║
║      4 ║  FF   ║    1   ║
║      4 ║  ss   ║    2   ║
║      4 ║  ss   ║    2   ║
╚════════╩═══════╩════════╝

You want DENSE_RANK instead of ROW_NUMBER :

SELECT Week
     , [Desc]
     , DENSE_RANK() OVER (PARTITION BY Week ORDER BY [Desc]) AS [Rank #]
FROM t

DENSE_RANK and RANK assign same value to rows with tie in the order by columns. DENSE_RANK in addition assigns "dense" rank numbers instead of "gapped" numbers.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM