简体   繁体   中英

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

Sample data:

在此处输入图片说明

Output should be:

输出数据

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM