[Solved] SQL query with order by clause


‘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;

1

solved SQL query with order by clause