customer_dim |
ptoduct_dim |
date_dim |
|
customer_street_address |
shipping_address |
product_name |
date |
customer_zip_code |
shipping_zip_code |
product_category |
month_name |
customer_city |
shipping_city |
|
quarter |
customer_state |
shipping_state |
|
year |
USE dw; SELECT product_category, year, quarter, month, SUM(order_amount) sum_order_amount FROM sales_order_fact a, product_dim b, date_dim c WHERE a.product_sk = b.product_sk AND a.order_date_sk = c.date_sk GROUP BY product_category , year , quarter , month CLUSTER BY product_category , year , quarter , month;查询结果如下图所示。分组查询的输出显示了每一行的度量(销售订单金额)都沿着年-季度-月的层次分组。
USE dw; -- 使用union all SELECT product_category, time, order_amount FROM ( SELECT product_category, case when sequence = 1 then concat('year: ', time) when sequence = 2 then concat('quarter: ', time) else concat('month: ', time) end time, order_amount, sequence, date FROM ( SELECT product_category, min(date) date, year time, 1 sequence, SUM(order_amount) order_amount FROM sales_order_fact a, product_dim b, date_dim c WHERE a.product_sk = b.product_sk AND a.order_date_sk = c.date_sk GROUP BY product_category , year UNION ALL SELECT product_category, min(date) date, quarter time, 2 sequence, SUM(order_amount) order_amount FROM sales_order_fact a, product_dim b, date_dim c WHERE a.product_sk = b.product_sk AND a.order_date_sk = c.date_sk GROUP BY product_category , year , quarter UNION ALL SELECT product_category, min(date) date, month time, 3 sequence, SUM(order_amount) order_amount FROM sales_order_fact a, product_dim b, date_dim c WHERE a.product_sk = b.product_sk AND a.order_date_sk = c.date_sk GROUP BY product_category , year , quarter , month) x CLUSTER BY product_category , date , sequence , time) y; -- 使用grouping__id函数 SELECT product_category, time, order_amount FROM ( SELECT product_category, case when gid = 3 then concat('year: ', year) when gid = 7 then concat('quarter: ', quarter) else concat('month: ', month) end time, order_amount, gid, date FROM ( SELECT product_category, year, quarter, month, min(date) date, SUM(order_amount) order_amount, CAST(grouping__id AS INT) gid FROM sales_order_fact a, product_dim b, date_dim c WHERE a.product_sk = b.product_sk AND a.order_date_sk = c.date_sk GROUP BY product_category , year , quarter , month with rollup ) x WHERE gid > 1 CLUSTER BY product_category , date , gid , time) y;
查询结果如下图所示。