SQL Question

How to select 1st and 2nd row instance in SQL table having the same value in another table?

Sample data:

enter image description here

Output should be:

Output Data

I want to ask what script in MSSQL I can run to get that kind of output. Hope somebody can help me I'm still new in SQL programming. Thank you so much in advance.

Answer

Use a CTE witha row_number():

with CTE as
(
select T1.*, row_number() over(partition by USERNAME order by TRANSACTION_TIME) X_ORD
from Table1 T1
)

select distinct 
       A1.USERNAME,
       A1.REGISTRATION_DATE, 
       A2.Transaction_Time as First_X, 
       A2.RELOAD_AMOUNT as First_R, 
       A2.CHANNEL as First_C, 
       A3.Transaction_Time as Second_X, 
       A3.RELOAD_AMOUNT as Second_R, 
       A3.CHANNEL as Second_C
from CTE A1
left join CTE A2
  on A1.USERNAME = A2.USERNAME
  and A2.X_ORD = 1
left join CTE A3
  on A1.USERNAME = A3.USERNAME
  and A3.X_ORD = 2
Comments