0

I need to create an aggregation for each housing type (column type) for each destination. There is a hierarchy (product->sub_product) and (category->sub_category) and also product can have different categories and each category can be linked to every product. But first a product need to be selected so the hierarchy is product(sub_product)->industry_category(industry_sub_category) I tried with the query below and all-all-all-all combinations for given destination and type is correct, but the other combinations are off. Any ideas what need to be changed or how to optimize?

WITH test_table AS (
SELECT
 CASE WHEN date between date_column between ’2025-01-01’ AND ‘2025-01-31 THEN ‘Jan’
    WHEN date between date_column between ’2025-02-01’ AND ‘2025-02-28 THEN ‘Feb’
ELSE ‘NA’ END AS target_month,
 IF(GROUPING(product_group) = 1, 'all', product_group) AS title_group,
 IF(GROUPING(product) = 1, 'all', product) AS title,
 IF(GROUPING(category) = 1, 'all', category) AS industry_category,
 IF(GROUPING(sub_category) = 1, 'all', sub_category) AS industry_sub_category,

 ‘destination’ AS dimension_type,
 destination AS dimension_value,
 ‘housing_type’ as related_type,
 type as related_value,


 sum(type_count) AS counter

FROM
 table_a

GROUP BY
GROUPING SETS(
 (target_month,product_group,
  product,
  category,
  sub_category,destination,type),
  (target_month,product_group,
  product,category,destination,type),
   (target_month,product_group,
  product,destination,type),
  (target_month,product_group,destination,type),
  (target_month,destination,type))

)
SELECT * FROM test_table;

Here are the logic I'm aiming for:[enter image description here](httpenter image description heres://i.sstatic.net/ZhDklNmS.jpg)enter image description here

1 Answer 1

0

I noticed your syntax in your CASE statement. The CASE statement has repeated BETWEEN keywords: date between date_column between .... I think this is incorrect SQL syntax. Try to fix the syntax. It should likely be date_column BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'.

Also, try adding a WHERE clause to filter the dates before the GROUP BY. This ensures only relevant data enters the aggregation pipeline.

1
  • Let me know if this has resolved your issue. If it did, an upvote or marking it as accepted would be appreciated as this helps the community.
    – jggp1094
    Commented Apr 15 at 19:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.