Created
February 23, 2023 03:29
-
-
Save carlineng/8eabab682ca80ad8ea2c77e8f30122c0 to your computer and use it in GitHub Desktop.
TPC-DS Query 36
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "tpcds.malloy" | |
query: store_sales + { | |
query: margin_agg is { | |
aggregate: | |
gross_margin is total_profit / total_ext_sales | |
} | |
} -> { | |
nest: margin_agg | |
nest: by_category is { | |
group_by: item.i_category | |
nest: margin_agg | |
nest: by_class is { | |
group_by: item.i_class | |
nest: margin_agg | |
} | |
} | |
where: | |
date_dim.d_year = 2001 | |
and store.s_state = 'TN' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH results AS | |
(SELECT sum(ss_net_profit) AS ss_net_profit, | |
sum(ss_ext_sales_price) AS ss_ext_sales_price, | |
(sum(ss_net_profit)*1.0000)/sum(ss_ext_sales_price) AS gross_margin , | |
i_category , | |
i_class , | |
0 AS g_category, | |
0 AS g_class | |
FROM store_sales , | |
date_dim d1 , | |
item , | |
store | |
WHERE d1.d_year = 2001 | |
AND d1.d_date_sk = ss_sold_date_sk | |
AND i_item_sk = ss_item_sk | |
AND s_store_sk = ss_store_sk | |
AND s_state ='TN' | |
GROUP BY i_category, | |
i_class) , | |
results_rollup AS | |
(SELECT gross_margin, | |
i_category, | |
i_class, | |
0 AS t_category, | |
0 AS t_class, | |
0 AS lochierarchy | |
FROM results | |
UNION SELECT (sum(ss_net_profit)*1.0000)/sum(ss_ext_sales_price) AS gross_margin, | |
i_category, | |
NULL AS i_class, | |
0 AS t_category, | |
1 AS t_class, | |
1 AS lochierarchy | |
FROM results | |
GROUP BY i_category | |
UNION SELECT (sum(ss_net_profit)*1.0000)/sum(ss_ext_sales_price) AS gross_margin, | |
NULL AS i_category, | |
NULL AS i_class, | |
1 AS t_category, | |
1 AS t_class, | |
2 AS lochierarchy | |
FROM results) | |
SELECT gross_margin, | |
i_category, | |
i_class, | |
lochierarchy, | |
rank() OVER ( PARTITION BY lochierarchy, | |
CASE | |
WHEN t_class = 0 THEN i_category | |
END | |
ORDER BY gross_margin ASC) AS rank_within_parent | |
FROM results_rollup | |
ORDER BY lochierarchy DESC NULLS FIRST, | |
CASE | |
WHEN lochierarchy = 0 THEN i_category | |
END NULLS FIRST, | |
rank_within_parent NULLS FIRST | |
LIMIT 100; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment