Skip to content

Instantly share code, notes, and snippets.

@artworkad
Created November 8, 2019 09:59
Show Gist options
  • Save artworkad/c471b9aff7142bf8d0c73d2e4b880c8d to your computer and use it in GitHub Desktop.
Save artworkad/c471b9aff7142bf8d0c73d2e4b880c8d to your computer and use it in GitHub Desktop.
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1 customer_id, -500 value,
DATE '2019-10-12' timestamp UNION ALL
SELECT 1, -300, '2019-10-11' UNION ALL
SELECT 1, -200, '2019-10-10' UNION ALL
SELECT 2, 200, '2019-09-10' UNION ALL
SELECT 2, 100, '2019-08-10' UNION ALL
SELECT 2, 50, '2019-07-10' UNION ALL
SELECT 1, 600, '2019-09-02'
), customers AS (
SELECT DISTINCT customer_id FROM `project.dataset.table`
), months AS (
SELECT month FROM (
SELECT DATE_TRUNC(MIN(timestamp), MONTH) min_month, DATE_TRUNC(MAX(timestamp), MONTH) max_month
FROM `project.dataset.table`
), UNNEST(GENERATE_DATE_ARRAY(min_month, max_month, INTERVAL 1 MONTH)) month
)
SELECT customer_id,
IFNULL(value, LAG(value) OVER(win)) value,
IFNULL(timestamp, DATE_ADD(LAG(timestamp) OVER(win), INTERVAL DATE_DIFF(month, LAG(month) OVER(win), MONTH) MONTH)) timestamp
FROM months, customers
LEFT JOIN (
SELECT DATE_TRUNC(timestamp, MONTH) month, customer_id,
ARRAY_AGG(STRUCT(value, timestamp) ORDER BY timestamp DESC LIMIT 1)[OFFSET(0)].*
FROM `project.dataset.table`
GROUP BY month, customer_id
) USING(month, customer_id)
WINDOW win AS (PARTITION BY customer_id ORDER BY timestamp DESC)
-- ORDER BY month DESC, customer_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment