I have a table with data structured like this. Each product ID has a list of element IDs--for each element, there is a dictionary including a list of elements and their assigned IDs. Not every element will have an ID on every product
| product_id | element_id |
|---|---|
| product_1 | {"FIRE": ["1630808"],"WATER": ["188028","234"],"SHADOW": ["213181"] |
For each product I'd like to be able to count how many of each element ID appear, in a table like this:
| product_id | fire_count | water_count | shadow_count | forest_count |
|---|---|---|---|---|
| product_1 | 1 | 2 | 1 | 0 |
I've tried using the LATERAL FLATTEN function with KEY and VALUE, but I'm getting duplicate results and wonder if there is a more crisp way of writing this type of query, especially because I also need to count instances where an ID does not appear.
My data is stored in Snowflake and I query it using Snowflake SQL.
Any advice? Thank you!