简体   繁体   English

每隔一行插入一列

[英]Insert every other row to a Column

I have this Table with one row Transaction Date the first row is the checkIn and the second one is the Checkout if we organized the result by date asc.如果我们按日期升序组织结果,我有这个表,其中一行是Transaction Date ,第一行是checkIn ,第二行是Checkout出。

I need to pass the second row value to another column named Checkout .我需要将第二行值传递给另一个名为Checkout的列。 This table has at least 1000 records此表至少有 1000 条记录

You can use row_number() :您可以使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by studentid order by transactiondate) as seqnum
      from t
     ) t
where seqnum = 2;

This assumes that only studentid is used to identify the "first" and "second" rows.这假定只有studentid用于标识“第一”和“第二”行。 If more columns are needed, add them to the partition by clause.如果需要更多列,请将它们添加到partition by子句中。

If the checkout date you need is the second (max) date grouped by reason and you want to single out this date then try:如果您需要的结帐日期是按原因分组的第二个(最大)日期,并且您想挑出此日期,请尝试:

select 
  studentID,
  reason,
  max(transactionDate) as checkoutDate
from student
group by
  reason

Try using the query below尝试使用下面的查询

With CteCheckOut as(
Select
ROW_NUMBER() over (Partition by studentID Order by studentID,transactionDate) as Rownumber,
*
From student
)
Select studentID, transactionDate as CheckOutDate
From CteCheckOut
Where Rownumber%2 = 0

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

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