2

我有以下数据:

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

4 回答 4

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
于 2012-12-04T11:48:46.870 回答
0

询问:

SQLFiddle示例

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 |
于 2012-12-05T12:41:33.617 回答
0

看看 TSQL RANK- MSDN 链接

于 2012-12-04T11:47:29.980 回答
0
select txn_number, 
       item_id, 
       desc, 
       row_number() over (partition by txn_number order by item_id) as unique_txn
from the_table
于 2012-12-04T11:48:15.507 回答