Skip to content

Instantly share code, notes, and snippets.

@romain9292
Created August 12, 2022 15:31
Show Gist options
  • Save romain9292/f0511916e6ece523275cb4c092f99c38 to your computer and use it in GitHub Desktop.
Save romain9292/f0511916e6ece523275cb4c092f99c38 to your computer and use it in GitHub Desktop.
[Perc Total - Over time - Part 2] How to compute a percentage of total in BigQuery using SQL #SQL #BigQuery
WITH
revenue_product AS (
SELECT
product_category,
DATE(DATE_TRUNC(order_date,MONTH)) AS order_month,
ROUND(SUM(product_revenue),0) AS revenue_per_category
FROM
`datastic.variables.base_table`
GROUP BY
1,
2)
-- Main Query
SELECT
*
FROM (
SELECT
*,
SAFE_DIVIDE(revenue_per_category,
SUM(revenue_per_category) OVER(PARTITION BY order_month)) AS ratio
FROM
revenue_product) a
WHERE
product_category IN ('Apparel',
'Office',
'Drinkware',
'Other')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment