Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

sql server - SQL query with order by clause

I have a table that has 3 columns. Product,Name,TimeStamp. At present, I don't have any rownumber column. If I fetch the record from the table, I will be using

select * 
from table 
order by Product,Name,TimeStamp. 

I will get some order of data. In that order I need another column that should show the row number. Simply put, I need a column that should tell me the row number based on the above order by query.

Is it possible to insert values based on some order? while creating table like that?

OPERATOR    PRODUCT USER NAME   TIME STAMP
1           INS1    1YHS        2018-08-15 09:02:33.000
1           INS1    1YHS        2018-08-15 10:46:17.000
2           INS1    1YHS        2018-08-15 11:01:28.000
2           INS1    1YHS        2018-08-15 17:07:47.000

Here if the operator is 1, license for product INS1 is taken and if the operator is 2 then the license for the same product is been returned. Same person can take more licenses. 1st row has the details of license been taken and the same license been returned and that information is stored in the 3rd row. for the 2nd row, the license returned information is stored in the 4th row.

I need to show the table like

OPERATOR    PRODUCT USER NAME   TIME STAMP
1           INS1    1YHS        2018-08-15 09:02:33.000
2           INS1    1YHS        2018-08-15 11:01:28.000
1           INS1    1YHS        2018-08-15 10:46:17.000
2           INS1    1YHS        2018-08-15 17:07:47.000
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

'Transaction' is a pair of take + return. It's identity is computed from source data so OPERATORs could be grouped the way you need. The query may fail on data with unpaired OPERATORs.

declare @tbl table (
OPERATOR int,   
PRODUCT varchar(50), 
[USER NAME] varchar(100),    
[TIME STAMP] datetime);

insert into @tbl(OPERATOR, PRODUCT, [USER NAME], [TIME STAMP]) values
 (1, 'INS1', '1YHS', '2018-08-15 09:02:33.000')
,(1, 'INS1', '1YHS', '2018-08-15 10:46:17.000')
,(2, 'INS1', '1YHS', '2018-08-15 11:01:28.000')
,(2, 'INS1', '1YHS', '2018-08-15 17:07:47.000');

select OPERATOR, PRODUCT, [USER NAME], [TIME STAMP]
from (
    select OPERATOR, PRODUCT, [USER NAME], [TIME STAMP]
        , row_number() over(partition by PRODUCT, [USER NAME], OPERATOR order by [TIME STAMP]) transId 
    from @tbl) t
order by PRODUCT, [USER NAME], transId, OPERATOR;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...