Coding skills here for learning
5 subscribers
266 photos
3 files
10 links
Download Telegram
pivot aggfunc flatten()
Coding skills here for learning
unbounded preceding n, precending, n current row n, following, n Unbounded following
unbounded preceding: from begining up to the current row

n, preceding: n rows before current row
n, following: means using current row and after n rows
unbounded following: start from current row and go in the end of the partition
when working with subqueries correlated you will self join is used in aggregated part
Certainly! Let's break down the SQL query step by step:

1. CTE `t1`:
- The first Common Table Expression (CTE) named t1 calculates the total sales (total_amt_usd) for each region by joining the sales_reps, accounts, orders, and region tables.
- It uses the GROUP BY clause to group the results by the region name (r.name).

   WITH t1 AS (
SELECT r.name region_name, SUM(o.total_amt_usd) total_amt
FROM sales_reps s
JOIN accounts a ON a.sales_rep_id = s.id
JOIN orders o ON o.account_id = a.id
JOIN region r ON r.id = s.region_id
GROUP BY r.name
)


2. CTE `t2`:
- The second CTE named t2 calculates the maximum total sales from t1.

   t2 AS (
SELECT MAX(total_amt) FROM t1
)


3. Main Query:
- The main query selects the region name (r.name) and the count of total orders (COUNT(o.total) total_orders) for each region.
- It joins the same set of tables (sales_reps, accounts, orders, region) and groups the results by the region name.
- The HAVING clause is used to filter the results based on the condition that the total sales (SUM(o.total_amt_usd)) for each region should be equal to the maximum total sales obtained from t2.

   SELECT r.name, COUNT(o.total) total_orders
FROM sales_reps s
JOIN accounts a ON a.sales_rep_id = s.id
JOIN orders o ON o.account_id = a.id
JOIN region r ON r.id = s.region_id
GROUP BY r.name
HAVING SUM(o.total_amt_usd) = (SELECT * FROM t2);


In summary, the query identifies regions where the total sales match the maximum total sales across all regions. It provides the region names and the count of total orders for those specific regions. The use of CTEs helps break down the complex query into more manageable parts for better readability and understanding.




CTE explanation
Rounding it means in pandas formating like f .2