[英]SQL average of sums?
I have a database consisting of many tables, 3 tables of interest here are ThemeParks
, Tickets
and TicketPrices
. 我有一个包含许多表格的数据库,这里有3个感兴趣的表格是ThemeParks
, Tickets
和TicketPrices
。
I currently have a query which displays the total ticket sales for each country: 我目前有一个查询,显示每个国家/地区的门票总销售量:
SELECT SUM(TicketPrices.price)
FROM TicketPrices, Tickets, ThemeParks
WHERE Tickets.TP_Code = ThemeParks.TP_Code
GROUP BY ThemeParks.TP_country
Query Result: 查询结果:
SUM(TicketPrices.price)
-----------------------
700
300
300
600
I would like to make a query that just displays the average of all of those values. 我想做一个查询,仅显示所有这些值的平均值。 How could I do this? 我该怎么办?
Just wrap it inside another query: 只需将其包装在另一个查询中:
SELECT AVG(price_sum)
FROM (SELECT SUM(TicketPrices.price) as price_sum
FROM TicketPrices, Tickets, ThemeParks
WHERE Tickets.TP_Code = ThemeParks.TP_Code
GROUP BY ThemeParks.TP_country) t
Also, consider switching over to ANSI join syntax. 另外,请考虑切换到ANSI连接语法。
The average is the sum divided by the count. 平均值是总和除以计数。 So: 所以:
SELECT SUM(tp.price) / COUNT(DISTINCT tp.TP_COUNTRY)
FROM TicketPrices tp JOIN
Tickets t
ON ??? JOIN
ThemeParks tp
ON t.TP_Code = tp.TP_Code;
The problem with your query, though, is the missing ON
clause. 但是,查询的问题是缺少ON
子句。 You should learn to use explicit JOIN
syntax. 您应该学习使用显式的JOIN
语法。 This will help you write correct queries in the future. 这将帮助您将来编写正确的查询。 A simple rule: Never use commas in the FROM
clause. 一个简单的规则: 永远不要在FROM
子句中使用逗号。 Always use explicit JOIN
syntax. 始终使用显式的JOIN
语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.