PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 23, 2022

[FIXED] How can update each row of a table based on two columns of it's previous row?

 October 23, 2022     join, sql-update, sqlite, sum, window-functions     No comments   

Issue

I have following table:

Id offset length
5000 0 5
5001 5 5
5002 10 4
5003 14 4
5010 23 5
5011 28 5

Offset value in each row is based on summation of offset and length of previous row. As you can see, 6 rows have been deleted between forth and fifth rows and I need to update again offset column based on regular way. My desired output would be as follow:

Id offset length
5000 0 5
5001 5 5
5002 10 4
5003 14 4
5010 18 5
5011 23 5

Is there a pure update SQL statement to achieve this in sqlite? I Appreciate any help.


Solution

If your version of SQLite is 3.33.0+ you can use the UPDATE ... FROM... syntax with SUM() window function:

UPDATE tablename AS t1
SET offset = t2.offset
FROM (
  SELECT Id, SUM(length) OVER (ORDER BY Id ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) offset
  FROM tablename 
) AS t2
WHERE t2.Id = t1.Id AND t2.offset IS NOT NULL;

See the demo.

For previous versions use a correlated subquery:

UPDATE tablename AS t1
SET offset = COALESCE(
  (SELECT SUM(t2.length) FROM tablename t2 WHERE t2.Id < t1.Id), 
  t1.offset
);

See the demo.



Answered By - forpas
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing