skip to Main Content

Tables

If I have ‘Table_A’ like above, is it possible to generate Table_B from it by using select sql only? I would like to keep the column ‘pc2’ and create the column ‘pc4’ to sum the values of ‘pc3’ and the value of ‘pc1’ from the consecutive row.

2

Answers


  1. Use LEAD() window function to get the next value of pc1 of each row:

    SELECT day, 
           pc2,
           pc3 + LEAD(pc1, 1, 0) OVER (ORDER BY day) AS pc4
    FROM Table_A;
    

    If you want to create a new table Table_B:

    CREATE TABLE Table_B AS
    SELECT day, 
           pc2,
           pc3 + LEAD(pc1, 1, 0) OVER (ORDER BY day) AS pc4
    FROM Table_A;
    
    Login or Signup to reply.
  2. You can try with the following SQL

    SELECT a.day,a.pc1,(a.pc3+b.pc2) AS pc4
    FROM TABLE_A AS a. TABLE_A AS b
    WHERE a.day=(b.day+1)
    ORDER BY a.day
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search