简体   繁体   中英

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.

I need to pass the second row value to another column named Checkout . This table has at least 1000 records

You can use 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. If more columns are needed, add them to the partition by clause.

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

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