简体   繁体   English

SQL聚合AVG语句

[英]SQL Aggregation AVG statement

Ok, so I have real difficulty with the following question. 好的,所以我很难回答以下问题。

Table 1: Schema for the bookworm database. 表1:bookworm数据库的架构。 Primary keys are underlined. 主键带有下划线。 There are some foreign key references to link the tables together; 有一些外键引用可以将表链接在一起。 you can make use of these with natural joins. 您可以将其与自然连接一起使用。

For each publisher, show the publisher's name and the average price per page of books published by the publisher. 对于每个出版商,请显示出版商的名称和出版商每页平均价格。 Average price per page here means the total price divided by the total number of pages for the set of books; 每页平均价格在这里是指总价格除以该套书籍的总页数; it is not the average of (price/number of pages). 它不是(价格/页数)的平均值。 Present the results sorted by average price per page in ascending order. 按每页平均价格升序显示结果。

Author(aid, alastname, afirstname, acountry, aborn, adied).
Book(bid, btitle, pid, bdate, bpages, bprice).
City(cid, cname, cstate, ccountry).
Publisher(pid, pname).
Author_Book(aid, bid).
Publisher_City(pid, cid).

So far I have tried: 到目前为止,我已经尝试过:

SELECT 
      pname,
      bpages, 
      AVG(bprice)
FROM book NATURAL JOIN publisher
GROUP BY AVG(bpages) ASC;

and receive 并收到

ERROR: syntax error at or near "asc" LINE 3: group by avg(bpages) asc; 错误:在语法错误或接近 “ASC” LINE 3:组由AVG(bpages)ASC;

You need ORDER BY clause and not GROUP BY to sort record. 您需要ORDER BY子句,而不是GROUP BY排序记录。 So change your query to: 因此,将查询更改为:

SELECT pname, AVG(bprice)
FROM book NATURAL JOIN publisher
GROUP by pname
ORDER BY AVG(bpages) ASC;

You can't group by an aggregate, at least not like that. 您无法通过聚合组,至少不是这样的。 Also don't use natural join, it's bad habit to get into because most of the time you'll have to specify join conditions. 也不要使用自然连接,这是个坏习惯,因为大多数时候您必须指定连接条件。 It's one of those things you see in text books but almost never in real life. 这是您在教科书中看到的事情之一,但在现实生活中几乎从未见过。

OK with that out of the way, and this being homework so I don't want to just give you an answer without an explanation, aggregate functions (sum in this case) affect all values for a column within a group as limited by the where clause and join conditions, so unless your doing every row you have to specify what column contains the values you are grouping by. 好的,不用担心,这是家庭作业,所以我不想在没有解释的情况下给您答案,聚合函数(在这种情况下为sum)会影响组中某列的所有值,但受where限制子句和联接条件,因此除非您在每一行中都必须指定要包含分组依据的值的列。 In this case our group is Publisher name, they want to know per publisher, what the price per page is. 在这种情况下,我们的组是发布者名称,他们想知道每个发布者的价格是多少。 Lets work out a quick select statement for that: 让我们为此制定一个快速选择语句:

select Pname as Publisher
  , Sum(bpages) as PublishersTotalPages
  , sum(bprice) as PublishersTotalPrice
  , sum(bprice)/Sum(bpages) as PublishersPricePerPage

Next up we have to determine where to get the information and how the tables relate to eachother, we will use books as the base (though due to the nature of left or right joins it's less important than you think). 接下来,我们必须确定从何处获取信息以及表格之间的关系,我们将使用书籍作为基础(尽管由于左右联接的性质,它并不如您想像的重要)。 We know there is a foreign key relation between the column PID in the book table and the column PID in the Publisher table: 我们知道书表中的列PID和发布者表中的列PID之间存在外键关系:

From Book B
  Join Publisher P on P.PID = B.PID

That's what is called an explicit join, we are explicitly stating equivalence between the two columns in the two tables (vs. implying equivalence if it's done in the where clause). 这就是被称为一个明确的加盟,我们都明确说明两列之间等价的两个表中(如果在where子句中的完成与暗示等值)。 This gives us a many to one relation ship, because each publisher has many books published. 这给我们带来了多对一的关系,因为每个出版商出版了许多书籍。 To see that just run the below: 要查看,只需运行以下命令:

select b.*, p.*
From Book B
  Join Publisher P on P.PID = B.PID

Now we get to the part that seems to have stumped you, how to get the many to one relationship between books and the publishers down to one row per publisher and perform an aggregation (sum in this case) on the page count per book and price per book. 现在,我们来了解一下似乎困扰您的部分,如何使书籍与出版商之间的多对一关系降到每个出版商一行,并对每本书的页数和价格进行汇总(在这种情况下为总和)每本书。 The aggregation portion was already done in our selection section, so now we just have to state what column the values our group will come from, since they want to know a per publisher aggregate we'll use the publisher name to group on: 聚合部分已经在我们的选择部分中完成了,所以现在我们只需要声明组值来自哪一列,因为他们想知道每个发布者的聚合,我们将使用发布者名称进行分组:

Group by Pname
Order by PublishersPricePerPage Asc

There is a little gotcha in that last part, publisherpriceperpage is a column alias for the formula sum(bprice)/Sum(bpages). 有在这最后部分有点疑难杂症,publisherpriceperpage用于使式总和(bprice)/萨姆(bpages)列别名。 Because order by is done after all other parts of the query it's unique in that we can use a column alias no other part of a query allows that, without nesting the original query. 因为order by是在查询的所有其他部分之后完成的,所以它的独特之处在于我们可以使用列别名,而没有嵌套原始查询的情况,查询的其他部分都不允许这样做。 so now that you have patiently waded through my explanation, here is the final product: 因此,既然您耐心地了解了我的解释,以下是最终产品:

select Pname as Publisher
  , Sum(bpages) as PublishersTotalPages
  , sum(bprice) as PublishersTotalPrice
  , sum(bprice)/Sum(bpages) as PublishersPricePerPage
From Book B
  Join Publisher P on P.PID = B.PID
Group by Pname
Order by PublishersPricePerPage Asc

Good luck and hope the explanation helped you get the concept. 祝你好运,希望解释帮助你得到的概念。

The ASC is part of the ORDER BY clause. ASCORDER BY子句的一部分。 You are missing the ORDER BY here. 您在这里缺少ORDER BY

Reference: http://www.tutorialspoint.com/sql/sql-group-by.htm 参考: http//www.tutorialspoint.com/sql/sql-group-by.htm

Base on what you're trying to achieve. 根据您要达到的目标。 You can try my query below. 您可以在下面尝试我的查询。 I used the stated formula in a CASE statement to catch the error when a bprice is divided by zero(0). 我用规定的公式中CASE语句捕获错误时bprice由零(0)分开。 Also I added ORDER BY clause in your query and there's no need for the AVG aggregates. 此外,我加入ORDER BY在查询子句和有没有必要对AVG聚集。

SELECT 
      pname,
      CASE WHEN SUM(bpages)=0 THEN '' ELSE SUM(bprice)/SUM(bpages) END price
FROM book NATURAL JOIN publisher
GROUP BY pname 
ORDER BY pname ASC;

You need Order By for sorting, which was missing: 您需要使用Order By进行排序,但缺少以下内容:

SELECT 
      pname,
      bpages, 
      AVG(bprice)
FROM book NATURAL JOIN publisher
GROUP BY pname, bpages
order by AVG(bpages) ASC;

Check this 检查一下

     SELECT pname, AVG(bprice)
FROM book NATURAL JOIN publisher
GROUP by pname
ORDER BY AVG(bpages)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM