Skip to content
Advertisement

Google BigQuery – Subtract SUMs of a column basing on values in another column

Hi I need 1 query to get top 10 country which has largest [total(import) – total(export)] for goods_type medicines between 2019 – 2020.

The data sample is as below:

The returned data should include country, goods_type, and the value of [total(imports) – total(export)].

I have come up with the query below, but I don’t know if it’s right or wrong, and I struggle to extend it to get other columns. I got an error telling select expression column ... not grouped or aggregated... in Google BigQuery console.

I appreciate any help! Thanks.

Advertisement

Answer

You can express this as a single query with GROUP BY, filtering, and conditional aggregation:

Note that this does not include YEAR in the SELECT because it is “aggregated away”.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement