I need to have row numbering where the ROW_NUMBER is the same for same value column: MFGPN (Same MFGPN will always be in sequence). I also need to maintain the original sequence by No.
Here's my table
No MFGPN
1 Z363700Z01
2 Z363700Z01
3 0119-960-1
4 1A3F1-0503-01
I tried using RANK() to achieve the desired but am running into trouble.
SELECT RANK() OVER(ORDER BY MFGPN) As [Item], MFGPN FROM Table1 ORDER BY [No] ASC
RESULT
Item MFGPN Desired Result
3 Z363700Z01 1
3 Z363700Z01 1
1 0119-960-1 2
2 1A3F1-0503-01 3
Appreciate you guys' expert advise. Thanks!
Use DENSE_RANK
window function instead of RANK
. Rank
will skip the sequence when there is a repetition of data Dense_Rank
will not.
SELECT MFGPN,
Dense_rank()OVER(ORDER BY m_no) as [Desired Result]
FROM (SELECT no,
MFGPN,
Min(no)OVER(partition BY MFGPN) AS m_no
FROM (VALUES (1,'Z363700Z01' ),
(2,'Z363700Z01' ),
(3,'0119-960-1' ),
(4,'1A3F1-0503-01')) tc (no, MFGPN))a
If no
is not unique then change DENSE_RANK
to
Dense_rank()OVER(ORDER BY m_no,MFGPN)
Result :
+---------------+----------------+
| MFGPN | Desired Result |
+---------------+----------------+
| Z363700Z01 | 1 |
| Z363700Z01 | 1 |
| 0119-960-1 | 2 |
| 1A3F1-0503-01 | 3 |
+---------------+----------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With