WITH
auditing_table AS (
SELECT *
FROM propertydb_staging.my_auditing
GROUP BY 1,2,3,4,5,6,7,8,9,10),
credit_usage_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) >= '2016-10-01'
AND section_code IN ('AD_CREDIT','AUTOREPOST')
AND action_code IN ('ACTIVATION_REPOST','ACTIVATION','AUTOREPOST','PREMIUM','REPOST')
GROUP BY 1,2,3,4,5),
action_table AS (
SELECT
EXTRACT(YEAR FROM time) AS year,
time,
agent_id,
SUM(CASE WHEN section_code = 'AD_CREDIT' AND action_code = 'REPOST' THEN credits_used ELSE 0 END) AS total_repost_credit,
SUM(CASE WHEN section_code = 'AD_CREDIT' AND action_code IN ('ACTIVATION_REPOST' ,'ACTIVATION') THEN credits_used ELSE 0 END) AS listing_activation_credit,
SUM(CASE WHEN section_code = 'AUTOREPOST' AND action_code = 'REPOST' THEN credits_used ELSE 0 END) AS autorepost_credit,
SUM(CASE WHEN section_code = 'AD_CREDIT' AND action_code = 'PREMIUM' THEN credits_used ELSE 0 END) AS spotlight_credit
FROM credit_usage_table
GROUP BY 1,2,3
)
SELECT
time,
agent_id,
total_repost_credit - autorepost_credit AS repost_credit,
listing_activation_credit,
autorepost_credit,
spotlight_credit
FROM action_table
ORDER BY 1,2,3