Reputation: 181
I have a question about SQL/BigQuery. I made a simple dataset in the screenshot that has 3 products and a total row (which is classified as a product as well). The "OTHER" product is calculated by substracting product A, B, C from TOTAL.
How can I write a query that would calculate "OTHER" for each day? In the screenshot in red is the result I would want, the rows in white is the data I have in BigQuery. I assume I have to use SUM() OVER with a UNION? Yet I havent figured it out
Upvotes: 1
Views: 3270
Reputation: 172994
Consider below
select * from your_table union all
select date, 'OTHER', sum(quantity * if(product = 'TOTAL', 1, -1))
from your_table
group by date
Upvotes: 1
Reputation: 1849
An option to solve using only SUM
and UNION ALL
:
SELECT * FROM table
UNION ALL
SELECT
date,
'OTHER' as product,
SUM(IF(product = 'TOTAL', quantity, 0))-SUM(IF(product != 'TOTAL', quantity, 0)) as quantity
FROM table
GROUP BY date
Upvotes: 2