sql - Postgresql 子查询包含错误
问题描述
我正在学习 SQL 课程,这是我的练习。我把它分成两个步骤(内部和外部声明)。在第三步中,我想将前面的步骤组合成一个带有子查询的查询。但它不起作用。有人可以帮我解决这个问题(甚至可能让我理解这个..)吗?太感谢了!
练习:[您的团队想知道支付最高总金额的前 5 名客户列表中支付的平均金额是多少] 支付最高总金额的前 5 名客户已经使用此查询进行了查询:
SELECT B.customer_id, B.first_name, B.last_name, D.city, E.country,
SUM(amount) AS total_payment
FROM payment A
INNER JOIN customer B ON A.customer_id = B.customer_id
INNER JOIN address C ON B.address_id = C.address_id
INNER JOIN city D ON C.city_id = D.city_id
INNER JOIN country E ON D.country_id=E.country_id
WHERE D.city IN ('Aurora', 'Atlixco', 'Xintai','Adoni', 'Dhule (Dhulia)', 'Kurashiki', 'Pingxiang', 'Sivas', 'Celaya', 'So Leopoldo')
GROUP BY B.customer_id, B.first_name, B.last_name, D.city, E.country
这应该做成一个子查询。它应该有别名 total_amount_paid。写一个外部语句来计算平均支付金额。将您的子查询添加到外部语句。它将出现在 SELECT、WHERE 或 FROM 子句中。(提示:在外部语句中引用子查询时,请确保使用子查询的别名“total_amount_paid”。)
第一步(内部语句)
(SELECT B.customer_id, B.first_name, B.last_name, D.city, E.country,
SUM(amount) AS total_payment
FROM payment A
INNER JOIN customer B ON A.customer_id = B.customer_id
INNER JOIN address C ON B.address_id = C.address_id
INNER JOIN city D ON C.city_id = D.city_id
INNER JOIN country E ON D.country_id=E.country_id
WHERE D.city IN ('Aurora', 'Atlixco', 'Xintai','Adoni', 'Dhule (Dhulia)', 'Kurashiki', 'Pingxiang', 'Sivas', 'Celaya', 'So Leopoldo')
GROUP BY B.customer_id, B.first_name, B.last_name, D.city, E.country) AS total_amount_paid
第二步(外部声明)
SELECT B.customer_id, B.first_name, B.last_name, D.city, E.country,
AVG(total_amount_paid) AS avg_amount_paid
GROUP BY avg_amount_paid
第三步(组合查询,出现了很多我无法修复的错误,因为我不明白我在做什么,基本上)
SELECT AVG (total_amount_paid) as average.total_amount_paid
FROM
(SELECT B.customer_id, B.first_name, B.last_name, D.city, E.country,
SUM(amount) AS total_payment
FROM payment A
INNER JOIN customer B ON A.customer_id = B.customer_id
INNER JOIN address C ON B.address_id = C.address_id
INNER JOIN city D ON C.city_id = D.city_id
INNER JOIN country E ON D.country_id=E.country_id
WHERE D.city IN ('Aurora', 'Atlixco', 'Xintai','Adoni', 'Dhule (Dhulia)', 'Kurashiki', 'Pingxiang', 'Sivas', 'Celaya', 'So Leopoldo')
GROUP BY B.customer_id, B.first_name, B.last_name, D.city, E.country) AS total_amount_paid
GROUP BY average.total_amount_paid
由于 GROUP BY 语句,它可能也是一团糟?老实说,我什至不明白 GROUP BY 是什么意思.. :D
解决方案
推荐阅读
- emscripten - 我如何告诉 Emscripten 记录它使用 Asyncify 处理的功能?
- android - 在 android studio 中查看模型状态:Kotlin
- javascript - 如何在 node.js 中包含默认模型作为参考名称?
- sql - 如何列出 SQL 中的特定记录?
- c# - 如何将请求内容解析为函数中的强类型?
- mysql - 将 timediff() 中的值转换为 mysql 的字符串
- python - 替代嵌套 for 循环
- laravel - 更新到 Nova 3.8 后,ID 字段从索引视图中消失了
- javascript - 从 React 功能组件中进行 API 调用
- flutter - 是否可以在 Flutter 中扩展 FCM?