我需要行编号,其中ROW_NUMBER对于相同的值列是相同的:MFGPN(相同的MFGPN将始终按顺序)。我还需要保留原始序列号
这是我的表
No MFGPN
1 Z363700Z01
2 Z363700Z01
3 0119-960-1
4 1A3F1-0503-01
我尝试使用RANK()来实现所需,但遇到了麻烦。
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
感谢你们'专家建议。谢谢!
答案 0 :(得分:10)
使用DENSE_RANK
窗口函数代替RANK
。当数据重复Rank
时,Dense_Rank
将跳过序列。
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
如果no
不唯一,请将DENSE_RANK
更改为
Dense_rank()OVER(ORDER BY m_no,MFGPN)
结果:
+---------------+----------------+
| MFGPN | Desired Result |
+---------------+----------------+
| Z363700Z01 | 1 |
| Z363700Z01 | 1 |
| 0119-960-1 | 2 |
| 1A3F1-0503-01 | 3 |
+---------------+----------------+
答案 1 :(得分:0)
您应该按mfgpn
对结果进行分区,以便具有相同mfgpn
的行按no
获得相同的排名和顺序。此外,使用dense_rank
可确保您不会跳过"任何级别:
SELECT DENSE_RANK() OVER(PARTITION BY [mfgpn] ORDER BY [no]) As [Item],
[mfgpm]
FROM Table1
ORDER BY [No] ASC
答案 2 :(得分:0)
select sum(case when MFGPN = prev_MFGPN then 0 else 1 end) over (order by No) as item
,MFGPN
from (SELECT lag(MFGPN) over (order by [No]) as prev_MFGPN
,[No]
,MFGPN
FROM Table1
) t
ORDER BY [No] ASC
+------+---------------+
| item | MFGPN |
+------+---------------+
| 1 | Z363700Z01 |
+------+---------------+
| 1 | Z363700Z01 |
+------+---------------+
| 2 | 0119-960-1 |
+------+---------------+
| 3 | 1A3F1-0503-01 |
+------+---------------+
答案 3 :(得分:0)
您可以尝试下面的代码段。 DENSE_RANK()在上面解释了这种情况下的最佳方法。
SELECT a.*,
DENSE_RANK() OVER(ORDER BY MFGPN DESC) RN
FROM
(SELECT 1 AS no, 'Z363700Z01' AS mfgpn FROM dual
UNION ALL
SELECT 2 AS no, 'Z363700Z01' AS mfgpn FROM dual
UNION ALL
SELECT 3 AS no, '0119-960-1' AS mfgpn FROM dual
UNION ALL
SELECT 4 AS no, '1A3F1-0503-01' AS MFGPN FROM dual
)a;
-------------------------------OUTPUT-------------------------------------------
NO MFGPN RN
1 Z363700Z01 1
2 Z363700Z01 1
4 1A3F1-0503-01 2
3 0119-960-1 3
--------------------------------------------------------------------------------
答案 4 :(得分:0)
尝试:我认为使用join
并比较值以获得所需的输出更加简单灵活,如下所示:
SELECT p.MFGPN,
Dense_rank()OVER(ORDER BY CASE WHEN p.MFGPN = tp.MFGPN THEN tp.num ELSE p.num END) AS [Desired Result]
FROM tmp_option p
LEFT JOIN tmp_option tp ON tp.num+1 = p.num
ORDER BY p.num ASC