WITH
auditing_table AS (
SELECT
time,
target_user_id,
object_id,
user_id,
section_code,
action_code,
old_value,
new_value
FROM propertydb_staging.my_auditing
GROUP BY 1,2,3,4,5,6,7,8),
spotlight_listing_table AS (
SELECT
time,
target_user_id AS agent_id,
object_id AS listing_id,
section_code,
action_code,
SUM(CAST(old_value AS INT64) - CAST(new_value AS INT64)) as credits_used
FROM auditing_table
WHERE DATE(time) >= '2019-02-11'
AND section_code = 'AD_CREDIT'
AND action_code = 'PREMIUM'
AND user_id != 610
GROUP BY 1,2,3,4,5
),
spotlight_subscription_detail AS (
SELECT
listing_id,
DATE(time) AS start_date,
DATE_ADD(DATE(time), INTERVAL 7 DAY) AS end_date
FROM spotlight_listing_table
)
SELECT
listing_id,
activation_date
FROM
UNNEST(GENERATE_DATE_ARRAY(DATE("2019-02-11"), DATE_ADD(DATE("2019-02-11"), INTERVAL 3 YEAR))) AS activation_date,
spotlight_subscription_detail
WHERE activation_date >= start_date
AND activation_date <= end_date
ORDER BY 1,2