SQL Server Ordering row number sequentially for columns that have same values

v2g6jxz6  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(57)

I have a table like this:
| No. | ReferenceNumber | TransactionTime | Amount | Source |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | 3099 | N/A | -1125 | A |
| 2 | 3099 | N/A | -1125 | B |
| 3 | 3100 | N/A | -375 | B |
| 4 | 3101 | 05:00 | -375 | A |
| 5 | 3101 | 05:00 | 2000 | B |
| 6 | 3101 | 06:00 | 2000 | A |
| 7 | 3102 | 06:00 | 2500 | B |

How to determine a number (in the No. column) sequentially for the above data using SQL Server? I appreciate for the help.

I've tried this T-SQL code:

SELECT 
    ROW_NUMBER() OVER (ORDER BY ReferenceNumber asc) No., 
    ReferenceNumber, TransactionTime, Amount, Source
FROM 
    aTable

I got the result like this:

No.ReferenceNumberTransactionTimeAmountSource
13099N/A-1125A
23099N/A-375B
33100N/A-1125B
4310105:00-375A
5310105:002000B
6310106:002500B
7310206:002000A

But, it's not the expectation like the above table.

yhxst69z

yhxst69z1#

Consider this approach

CREATE TABLE #Transactions([No.] int identity(1, 1), ReferenceNumber INT
  ,TransactionTime Varchar(15), Amount int, Source Varchar(1))    ;

INSERT into #Transactions
SELECT ReferenceNumber, TransactionTime, Amount, Source
FROM aTable;

SELECT * FROM #Transactions
rekjcdws

rekjcdws2#

Consider this:

DECLARE @Table TABLE (No INT, ReferenceNumber INT, TransactionTime TIME, Amount INT,    Source VARCHAR(1));
INSERT INTO @Table (No, ReferenceNumber, TransactionTime, Amount, Source) VALUES
(1, 3099, NULL   , -1125, 'A'),
(2, 3099, NULL   , -1125, 'B'),
(3, 3100, NULL   , -375 , 'B'),
(4, 3101, '05:00', -375 , 'A'),
(5, 3101, '05:00', 2000 , 'B'),
(6, 3101, '06:00', 2000 , 'A'),
(7, 3102, '06:00', 2500 , 'B');

SELECT *, ROW_NUMBER() OVER(ORDER BY ReferenceNumber, TransactionTime, Source)
  FROM @Table;

Here we've just added some addition columns to the ROW_NUMBERORDER .

13099-1125A1
23099-1125B2
33100-375B3
4310105:00:00.0000000-375A4
5310105:00:00.00000002000B5
6310106:00:00.00000002000A6
7310206:00:00.00000002500B7

相关问题