I have a table in BigQuery where I would like to be able to group according to some type of mapping file, for example if I had the following
Product Code | Country | Sales |
---|---|---|
AA1 | US | 5 |
AA2 | US | 10 |
AA1 | UK | 15 |
BB1 | US | 20 |
BB2 | US | 25 |
BB2 | UK | 25 |
and the following mapping
[AA1, AA2] > AA1
[BB1, BB2] > BB1
I would ideally be looking to get something along the following:
Product Code | Country | Sales |
---|---|---|
AA1 | US | 15 |
AA1 | UK | 15 |
BB1 | US | 45 |
BB1 | UK | 25 |
except obviously on a much larger scale. I’m wondering if there is a way to do this purely in SQL
2
Answers
You may aggregate using a
CASE
expression, which does the mapping:If you have a more complex mapping than this, then it might be better to create a bona-fide table which contains all the mappings, then join to this from your main table.
Employing a mapping table appears to be a simple join eg
But you are losing the fact that different products can appear within a group.