WITH
auditing_table AS (
SELECT
time,
target_user_id,
object_id,
section_code,
action_code,
old_value,
new_value
FROM propertydb_staging.sg_auditing
GROUP BY 1,2,3,4,5,6,7)
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-24'
AND section_code = 'AD_CREDIT'
AND action_code = 'PREMIUM'
GROUP BY 1,2,3,4,5
-----------
-- SELECT
-- listing_id,
-- activation_date
-- FROM final_table
-- WHERE listing_id IN (29060586,29230808,29249987)
-- -- ORDER BY 2 DESC
-- ORDER BY 1,2