SQL Query获取唯一序列

时间:2012-12-04 11:42:14

标签: sql sql-server

我有以下数据:

Txn Nmbr    Item ID     Desc
4           1111        Test 1
6           2222        Test 2
6           3333        Test 3
7           4444        Test 4
7           5555        Test 5
7           6666        Test 6

我希望所有上述数据都包含一个更多的列,这是每个< Txn Nmbr'的唯一序列号。因此,所需的输出是,

Txn Nmbr    Item ID     Desc        Unique Txn
4           1111        Test 1      1
6           2222        Test 2      2
6           3333        Test 3      2
7           4444        Test 4      3
7           5555        Test 5      3
7           6666        Test 6      3

请帮帮我!提前谢谢!

4 个答案:

答案 0 :(得分:1)

请尝试:

DECLARE @table as TABLE(TxnNmbr INT, ItemID INT, Descr NVARCHAR(50))

insert into @table values (4, 1111, 'Test1')
insert into @table values (6, 2222, 'Test2')
insert into @table values (6, 3333, 'Test3')
insert into @table values (7, 4444, 'Test4')
insert into @table values (7, 5555, 'Test5')
insert into @table values (7, 6666, 'Test6')

SELECT
   *,
   DENSE_RANK() OVER (ORDER BY [TxnNmbr]) AS [Unique Txn]
FROM @table

答案 1 :(得分:0)

查看TSQL RANK - MSDN link

答案 2 :(得分:0)

select txn_number, 
       item_id, 
       desc, 
       row_number() over (partition by txn_number order by item_id) as unique_txn
from the_table

答案 3 :(得分:0)

查询:

<强> SQLFiddleExample

SELECT
t1.*,
(SELECT COUNT(*)
 FROM tbl t2
 WHERE t1.[Txn Nmbr] = t2.[Txn Nmbr]) as [Unique Txn]
FROM tbl t1

结果:

| TXN NMBR | ITEM ID |   DESC | UNIQUE TXN |
--------------------------------------------
|        4 |    1111 | Test 1 |          1 |
|        6 |    2222 | Test 2 |          2 |
|        6 |    3333 | Test 3 |          2 |
|        7 |    4444 | Test 4 |          3 |
|        7 |    5555 | Test 5 |          3 |
|        7 |    6666 | Test 6 |          3 |