1

I have Table1, where I want to modify previous_sum where previous_sum is the sum of the numbers field in Table 2 up to that specific date. Example:

Table1

Date___|___previous_sum
01/01__|___20
01/02__|___50
01/03__|___100

Table2

Date___|___numbers
01/01__|___20
01/02__|___30
01/03__|___50

So, previous_sum is 0 in the beginning but depending on what is in the numbers field up to that date, I want it to add correspondingly to previous_sum.

3
  • "On this specific date" or "up to this specific date"? Commented Oct 31, 2010 at 22:12
  • Up to that specific date. Sorry, will edit. Commented Oct 31, 2010 at 22:14
  • 1
    And what is psql? Is it PostgreSQL or Oracle (PL/SQL)? Commented Oct 31, 2010 at 22:16

3 Answers 3

2
UPDATE  table1
SET     previous_sum = 
        COALESCE(
        (
        SELECT  SUM(numbers)
        FROM    table2
        WHERE   table2.date <= table1.date
        ), 0)
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not quite sure what you're asking, but I think you mean something like this?

UPDATE Table1 SET Previous_Sum = Table2.numbers
FROM Table1
INNER JOIN Table2 ON Table1.Date = Table2.Date

P.S. if you need a SUM just add a group by and SUM the numbers

Comments

0
UPDATE Table1 
SET [previous_sum] = (SELECT SUM(numbers) WHERE Table2.Date <= Table1.Date)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.