You are a database expert and SQL optimizer. You will be given a SQL query and its…
- User
You are a database expert and SQL optimizer. You will be given a SQL query and its rewritten variant. The rewritten query improves performance upon the original while maintaining equivalence. Your task is to create a new pair of original and rewritten queries that invoke a similar rewrite.
[ORIGINAL QUERY]
SELECT c.* FROM customer c WHERE c.address_id IN (SELECT a.address_id FROM address) and c.address_id in (SELECT a.address_id FROM address WHERE a.pin_code = '560012');[REWRITTEN QUERY]
SELECT c.* FROM customer c WHERE c.address_id IN (SELECT a.address_id FROM address WHERE a.pin_code = '560012');Now, consider the TPC-DS schema and create a new original and equivalent rewritten query pair such that the rewrite operation is similar to the provided demonstration.Keep the following points in mind while creating the new query pair:
- The original query must contain CTEs.
- The original query must make use of the following fact tables: ['web_sales', 'store_returns']. Below is the join graph for these fact tables: ['web_sales(ws_web_page_sk) references web_page(wp_web_page_sk);', 'web_sales(ws_warehouse_sk) references warehouse(w_warehouse_sk);', 'web_sales(ws_bill_hdemo_sk) references household_demographics(hd_demo_sk);'] ['store_returns(sr_return_time_sk) references time_dim(t_time_sk);', 'store_returns(sr_customer_sk) references customer(c_customer_sk);', 'store_returns(sr_store_sk) references store(s_store_sk);']
- The original query must employ 4 joins.
- The original query must employ the following aggregate functions: ['sum'].
- The original query must employ the following operators in its WHERE clause: [].
- The rewritten query must be equivalent to the original query, and must follow a similar rewrite pattern as in the given example. Enclose the original and rewritten queries within
and.
- Assistant
[ORIGINAL QUERY]
WITH sales_data AS ( SELECT ws_web_page_sk, ws_warehouse_sk, ws_bill_hdemo_sk, ws_net_profit FROM web_sales ), return_data AS ( SELECT sr_return_time_sk, sr_customer_sk, sr_store_sk, sr_net_loss FROM store_returns ), page_data AS ( SELECT wp_web_page_sk, wp_rec_start_date FROM web_page WHERE wp_type = 'content' ), customer_data AS ( SELECT c_customer_sk, c_customer_id FROM customer ) SELECT sum(ws.ws_net_profit) as total_net_profit FROM sales_data ws JOIN page_data wp ON ws.ws_web_page_sk = wp.wp_web_page_sk JOIN return_data sr ON sr.sr_customer_sk = ( SELECT c_customer_sk FROM customer ) JOIN warehouse w ON ws.ws_warehouse_sk = w.w_warehouse_sk WHERE sr.sr_net_loss < 100 AND sr.sr_store_sk IN (SELECT s_store_sk FROM store) AND wp.wp_rec_start_date BETWEEN '2002-01-01' AND '2002-12-31' GROUP BY ws.ws_warehouse_sk;