我正在尝试在SQL Server 2012的视图中插入一个新列,为每个唯一TxnID
分配一个新号码。
目前,TxnID
长度为28个字符。如果我可以为每个TxnID
分配一个以“1”开头的新号码,那就太棒了。
Current TxnID
-------------------------
2010100009000010000006783
2010100009000010000006784
2010100009000010000006785
2010100009000010000006785
所需的TxnID
1
2
3
3
答案 0 :(得分:1)
使用可能有帮助的排名函数rank()
select *, rank() over (order by TxnID) TxnID from table
答案 1 :(得分:0)
使用ROW_NUMBER()
CREATE VIEW DBO.Vw_MyView
AS
SELECT
TxnID = ROW_NUMBER() OVER(ORDER BY TxnID),
*
FROM YourTable
答案 2 :(得分:0)
我们可以使用很多方法 -
- RANK()
SELECT * , RANK() OVER (ORDER BY [Current TxnID]) rowNumx FROM (
SELECT '2010100009000010000006783' [Current TxnID] UNION ALL
SELECT '2010100009000010000006784' UNION ALL
SELECT '2010100009000010000006785' UNION ALL
SELECT '2010100009000010000006785' )p
- DENSE_RANK
SELECT * , DENSE_RANK() OVER (ORDER BY [Current TxnID]) rowNumx FROM (
SELECT '2010100009000010000006783' [Current TxnID] UNION ALL
SELECT '2010100009000010000006784' UNION ALL
SELECT '2010100009000010000006785' UNION ALL
SELECT '2010100009000010000006785' )p
- 其他
;WITH CTE AS
(
SELECT '2010100009000010000006783' [Current TxnID] UNION ALL
SELECT '2010100009000010000006784' UNION ALL
SELECT '2010100009000010000006785' UNION ALL
SELECT '2010100009000010000006785'
)
SELECT [Current TxnID], rowNumx = ( SELECT COUNT(*)+1 FROM CTE c1 WHERE c1.[Current TxnID] < c.[Current TxnID] )
FROM CTE c
OUTPUT For all
/*------------------------
OUTPUT
------------------------*/
Current TxnID rowNumx
------------------------- --------------------
2010100009000010000006783 1
2010100009000010000006784 2
2010100009000010000006785 3
2010100009000010000006785 3
(4 row(s) affected)