数据库
首页 > 数据库> > SQL

SQL

作者:互联网

 

WITH的使用

 

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),

t2 AS (
SELECT MAX(total_amt)
FROM t1)


SELECT r.name, SUM(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);

WITH t1 AS(
SELECT r.name region_name, SUM(o.total_amt_usd) total_amt, SUM(o.total) total_qty
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),

t2 AS(
SELECT MAX(total_amt) total_amt
FROM t1)

SELECT t1.region_name, t1.total_qty
FROM t1
JOIN t2
ON t1.total_amt = t2.total_amt

   

 

标签:name,region,amt,SQL,total,id,SELECT
来源: https://www.cnblogs.com/whateveranyhow/p/15509018.html