如何在SQL查询中生成序列号?

时间:2018-01-20 04:43:46

标签: sql sql-server

Id  Desc     Sequenceno
-----------------------------
84  TEST         1
84  TEST2        2
84  TEST3        3
85  IPhone       1
85  IPhone1      2
87  Nokia        1
88  Vivo         1
88  Vivo1        2

我有IdDesc列。如何获得上面的Sequenceno列?

先谢谢。

2 个答案:

答案 0 :(得分:4)

使用ANSI标准row_number()函数:

select t.*, row_number() over (partition by id order by [desc]) as seqnum
from t;

答案 1 :(得分:1)

试试这个:

SELECT
  Id, [Desc], 
  ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Id) AS Sequenceno
FROM #Temp;