Postgres/SQL: How Do I Include the Current Row's Value Of Another Column In a Function Where The Function Finds A Record From Another Table?

Viewed 36

Please go easy on me as I'm learning SQL from scratch pretty recently haha.

Here's what I have going on right now (function works, update does not due to the 'u.name' can't reference the table in this spot according to the error. Added what I thought would work and hopefully you can see where I was going): skip to the end for the question

CREATE OR REPLACE FUNCTION getLastSetDate(selected_sub_bucket character varying)
    RETURNS int AS $$
    SELECT max(coalesce(
        (SELECT transaction_date
           FROM (
               SELECT *, row_number() over(ORDER BY transaction_date DESC
                 ) as position 
               FROM bucket_transactions
           ) RESULT 
        WHERE type = 'SET' and sub_bucket = selected_sub_bucket
        ORDER BY transaction_date DESC limit 1),
    0))
    $$ LANGUAGE sql;

UPDATE buckets u
    SET amount = a.total
FROM (WITH selectedRows as (select * from bucket_transactions where transaction_date > getLastSetDate(u.name))
    SELECT sub_bucket, SUM(amount) as total
    FROM selectedRows
    WHERE transaction_date > getLastSetDate(u.name)
    GROUP BY sub_bucket
     ) a 
WHERE u.name = a.sub_bucket and u.bucket_type = 'sub';

I have two tables, one being a 'bucket_transactions' table, and the other being a 'buckets' table. The buckets table contains the name, and the sum of all transactions' amounts under that bucket past a certain date. To find this date, I'm searching for the most recent transaction under that bucket or sub_bucket with the transaction type being 'SET' (setting the value of the bucket).

TABLE: buckets

name bucket_type amount
Living Expenses primary -143.00
Food sub -89.00
Gas sub -54.00

TABLE: bucket_transactions

bucket sub_bucket type transaction_date amount
Living Expenses Food SET 1662593637 0.00
Living Expenses Food EXPENSE 1662593954 -89.00
Living Expenses Gas EXPENSE 1662537592 -54.00

My question is, how would I change my code in order for each bucket to start at the 'SET' transaction and get the sum past of the amounts past that transaction date? Each bucket/sub_bucket would have a different SET date, if any. I'm looking to input into the function the current row's name, even though the script is updating the amount column.

Appreciate your time!

0 Answers
Related