I have a query in snowflake that works as expected but I feel like there's gotta be a better way of doing this, so I'm checking if anyone has a better and more efficient solution to this.
I want to count how many users have SA4 and SA5. Then check if they are multi_unit or not. For the ones that are multi_unit, count how many of each of the other ST products they have.
Original Table:
AB4_ind | AB5_ind | Multi_unit | AB300_ind | AB10_ind | AB20_ind | AB30_ind |
---|---|---|---|---|---|---|
1 | 0 | 1 | 1 | 1 | 0 | 1 |
1 | 0 | 0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 0 | 0 | 0 | 0 |
0 | 1 | 1 | 1 | 0 | 0 | 0 |
1 | 1 | 1 | 0 | 0 | 1 | 0 |
0 | 1 | 1 | 0 | 0 | 1 | 1 |
Output table wanted with query:
Product | CNT | Multi | AB300 | AB10 | AB20 | AB30 |
---|---|---|---|---|---|---|
AB4 | 3 | 1 | 1 | 1 | 0 | 1 |
AB5 | 4 | 3 | 1 | 0 | 2 | 1 |
Here's the query that works, but I feel like there's gotta be a better way of doing this. Please let me know your thoughts :) Appreciated
SELECT
'AB4' AS Product,
COUNT(*) AS CNT,
SUM(CASE WHEN MULTI_UNIT = 1 THEN 1 ELSE 0 END) AS MULTI,
SUM(AB300_IND) AS AB300,
SUM(AB10_IND) AS AB10,
SUM(AB20_IND) AS AB20,
SUM(AB30_IND) AS AB30,
FROM TABLE.VIEW.MAW
WHERE AB4_IND = 1
GROUP BY 1
UNION
SELECT
'AB5' AS Product,
COUNT(*) AS CNT,
SUM(CASE WHEN MULTI_UNIT = 1 THEN 1 ELSE 0 END) AS MULTI,
SUM(AB300_IND) AS AB300,
SUM(AB10_IND) AS AB10,
SUM(AB20_IND) AS AB20,
SUM(AB30_IND) AS AB30,
FROM TABLE.VIEW.MAW
WHERE AB5_IND = 1
GROUP BY 1