Skip to content

Instantly share code, notes, and snippets.

@mazsam
Last active July 5, 2024 07:06
Show Gist options
  • Save mazsam/7a0e5aea25acf4ec0b426e65a33b1c5c to your computer and use it in GitHub Desktop.
Save mazsam/7a0e5aea25acf4ec0b426e65a33b1c5c to your computer and use it in GitHub Desktop.
CREATE VIEW view_monthly_pricing AS
SELECT
COALESCE(asset_data.company_id, license_data.company_id) AS company_id,
COALESCE(asset_month, license_month) AS month,
COALESCE(total_asset_price, 0) AS total_asset_price,
COALESCE(total_license_price, 0) AS total_license_price,
COALESCE(total_asset_price, 0) + COALESCE(total_license_price, 0) AS total_price
FROM
(SELECT
company_id,
DATE_TRUNC('month', acquired_at) AS asset_month,
SUM(price) AS total_asset_price
FROM
assets
WHERE deleted_at IS NULL
GROUP BY
DATE_TRUNC('month', acquired_at), company_id) AS asset_data
FULL OUTER JOIN
(SELECT
company_id,
DATE_TRUNC('month', purchased_at) AS license_month,
SUM(price) AS total_license_price
FROM
licenses
WHERE deleted_at IS NULL
GROUP BY
DATE_TRUNC('month', purchased_at), company_id) AS license_data
ON
asset_data.company_id = license_data.company_id AND
asset_data.asset_month = license_data.license_month
ORDER BY
month;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment