📘 SQL 与聚合
SQL
一个 SQL 查询语句通常以 SELECT
开始,在这里我们列出所需的字段,然后是 FROM
子句来指定将返回行的表(或在本例中为子查询)。我们可以使用 WHERE
进行筛选,并使用 GROUP
对数据进行分组。
我们从读取 SQL 需从嵌套中理解整个语句的含义。如果嵌套过多,则不易理解。
SELECT
city,
SUM(annual_spend) Total_Spend,
AVG(annual_spend) Average_Spend,
MAX(annual_spend) Max_Spend,
COUNT(annual_spend) customers
FROM (
SELECT t1.city, customer.annual_spend
FROM customer
LEFT JOIN (
SELECT address.address_id, city.city,
address.customer_id, address.location
FROM address LEFT JOIN city
ON address.city_id = city.city_id
) AS t1
ON
(customer.customer_id = t1.customer_id AND
t1.location = "home")
) AS t2
GROUP BY city;