SQL - Update a table using LAG and based on another column

Viewed 173

I have a dashboard with python and dash/plotly that receives inputs from the user and then run a query on Google BigQuery.

One of the queries updates a column (PAY_FT), uses other column (PAY_CLEAN) and a string input from the dashboard.

    DECLARE cpi STRING DEFAULT "C";
    UPDATE `xx.yy.zz` t
    SET
    PAY_FT = s.PAY_FT
    FROM
    (
    SELECT
        RN,
        CASE
        WHEN RN = 1 AND cpi = "S" AND PAY_SHALE_COR = "PAY" THEN 1
        WHEN RN = 1 AND cpi = "C" AND PAY_CLEAN = "PAY" THEN 1
        WHEN RN = 1 THEN 0
        WHEN RN > 1 AND cpi = "S" AND PAY_SHALE_COR = "PAY" THEN 0.2 + (LAG(PAY_FT, 1) OVER(ORDER BY RN))
        WHEN RN > 1 AND cpi = "C" AND PAY_CLEAN = "PAY" THEN 0.2 + (LAG(PAY_FT, 1) OVER(ORDER BY RN))
        ELSE (LAG(PAY_FT, 1) OVER(ORDER BY RN))
        END
        AS PAY_FT
    FROM
        `xx.yy.zz`
    WHERE
        DEPTH_M IS NOT NULL
    )
    s
    WHERE
    t.RN = s.RN

But it's not working as intended. This query returns the following:

enter image description here

It works until DEPTH_M = 102.2, but after that it dows not return the 0.4 from the previous row. So, for example, if we had a "PAY" in DEPTH_M = 103.2, until 103.0 should return 0.4 and in 103.2 it should be 0.6.

How can I fix it?

Here's a sample of my data: SAMPLE.csv

My desired outpu should be:

DEPTH_M PAY_CLEAN PAY_FT
101.2 PAY 0.2
101.4 PAY 0.4
101.6 - 0.4
101.8 - 0.4
102.0 - 0.4
102.2 - 0.4
102.4 - 0.4
102.6 - 0.4
102.8 - 0.4
103.0 - 0.4
103.2 - 0.4
103.4 - 0.4

Let's say that we got another PAY on another row, the output should be:

DEPTH_M PAY_CLEAN PAY_FT
101.2 PAY 0.2
101.4 PAY 0.4
101.6 - 0.4
101.8 - 0.4
102.0 - 0.4
102.2 - 0.4
102.4 - 0.4
102.6 - 0.4
102.8 - 0.4
103.0 PAY 0.6
103.2 - 0.6
103.4 - 0.6

Thanks in advance.

1 Answers

on the second thought you can go with this query which is much simpler and does what you want and you don't need to check for RN :

SELECT RN
    ,0.2 * COUNT(CASE WHEN (cpi = "S" AND PAY_SHALE_COR = "PAY") 
              OR (cpi = "C" AND PAY_CLEAN = "PAY") THEN 1 END) OVER (ORDER BY RN) 
 + SUM(CASE WHEN RN = 1 AND ((cpi = "S" AND PAY_SHALE_COR = "PAY") 
   OR (cpi = "C" AND PAY_CLEAN = "PAY")) THEN 0.8 ELSE 0 end) OVER () NEW_Pay_FT
FROM `xx.yy.zz`
WHERE DEPTH_M IS NOT NULL
Related