select district,
city,
postal_code,
(
select sum(amount) as revenue
from payment,
address
group by postal_code
)
from sakila.address,
sakila.city,
sakila.payment
where address.city_id = city.city_id
group by district,
city,
postal_code
order by district,
postal_code;
上面是我的sql语句。我有错误代码1242.我不明白为什么我有错误。我试图通过邮政编码计算总收入,以及填写区,城市,邮政编码。
你能告诉我什么是错的以及如何解决它?
提前谢谢。
答案 0 :(得分:0)
尝试以下方法......
SELECT address.district,
city.city,
address.postal_code,
SUM( amount ) AS revenue
FROM address
JOIN city ON address.city_ID = city.city_ID
JOIN customer ON address.address_ID = customer.address_ID
JOIN payment ON customer.customer_ID = payment.customer_ID
GROUP BY district, city, postal_code
ORDER BY district, postal_code;
答案 1 :(得分:0)
您需要将其设为相关子查询,而不是分组查询。
select district,
city,
postal_code,
(
select sum(amount) as revenue
from payment,
address
where postal_code = sakila.address.postal_code
)
您还需要payment
和address
表之间的连接条件,否则它们将在它们之间创建完整的交叉产品。您还需要主查询中payments
表的连接条件。
您应该学习使用ANSI JOIN语法编写查询,然后您不太可能忘记加入条件。而不是使用相关子查询,您只需加入payment
。我使用了LEFT JOIN
,因此当特定位置没有客户或付款时,您将获得revenu = 0
。
完整查询应为:
SELECT district, city, postal_code, IFNULL(SUM(amount), 0) AS revenue
FROM address AS a
JOIN city AS c ON a.city_id = c.city_id
LEFT JOIN customer AS cus ON cus.address_id = a.address_id
LEFT JOIN payment AS p ON p.customer_id = c.customer_id
GROUP BY district, city, postal_code
ORDER BY district, postal_code