简体   繁体   English

如何在另一个表中选择具有相同值的SQL表中的第一行和第二行实例?

[英]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. 我想问一下我可以运行哪种MSSQL脚本来获得这种输出。 Hope somebody can help me I'm still new in SQL programming. 希望有人能帮到我,我对SQL编程还是很陌生。 Thank you so much in advance. 提前非常感谢您。

Use a CTE witha row_number(): 使用带有row_number()的CTE:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在sql中比较同一表的第一条记录中的列A和第二条记录中的列B - How to compare columnA in 1st record and columnB in 2nd record of a same table in sql 如何连接两个SQL表,将第二个表中的值放入第一个表中的列? - How can I join two SQL tables, putting a value from the 2nd table into a column in the 1st? 如何在 SQL 服务器中从第一个和第二个表中获取匹配记录,并且仅从第一个表中获取不匹配记录,该服务器已加入 1 个字段 - How to get a a matching records from 1st and 2nd table and only non matching records from 1st table in SQL Server having joined by 1 field 如果第 2 个表中存在第 1 个表的值,则用第 1 个和第 2 个表的总和更新第 2 个表的值,否则将第一个表数据插入到第 2 个表 - If value of 1 table exists in the 2nd table, update the 2nd table value with sum of 1st and 2nd tables, else insert 1st table data to 2nd table T-SQL从第一个选择的值在第二个选择联合的每一行 - T-SQL Value from 1st select on each row in 2nd select of a union all SQL查询要在表上进行迭代,以计算在其字段之一中具有相同值的第一条记录和第二条记录之间的时间差? - SQL query to iterate on a table to calculate the time difference between the 1st and 2nd record that have the same value in one of their fields? 想要查询连接第一个表的第一行和第二个表的前两列 - want query to connect 1st table 1st row and 2nd table first two column 根据第一和第二表进行更新 - Update based of 1st and 2nd table 从第一张表中选择数据并获得第二张表的字段,其中表1中有2列 - select data from 1st table and get the 2nd table's field for 2 columns in table 1 需要SQL查询帮助-第一个表中的多行应与第二个表中的多个表匹配 - SQL Query help needed - Multiple rows in 1st table should match to multiple table in 2nd table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM