首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PSQL聚合函数

PSQL聚合函数
EN

Stack Overflow用户
提问于 2018-07-08 03:52:24
回答 3查看 179关注 0票数 0

我在大学的一个SQL班,我们正在使用PSQL。

供参考的表格。

代码语言:javascript
复制
     Table "public.author"
   Column   |  Type   | Modifiers 
------------+---------+-----------
 au_id      | numeric | not null
 first_name | text    | not null
 last_name  | text    | not null
 year_born  | numeric | not null

     Table "public.book"
 Column |  Type   | Modifiers 
--------+---------+-----------
 title  | text    | not null
 year   | numeric | not null
 isbn   | text    | not null
 pub_id | numeric | not null

我遇到的问题是:显示1990年至1993年出版的所有书籍的作者姓名、书名和出版年份。将作者名称显示为“最后”、“第一”(中间有逗号和空格)。按出版年份对输出进行排序。

输出:

代码语言:javascript
复制
select concat(last_name, ',', first_name) as name, title, year from author, book where year >= 1990 and year <= 1993 group by year order by year;

错误:列"author.last_name“必须出现在GROUP子句中,或者在聚合函数行1中使用:选择concat(last_name,',',first_name)作为名称、标题、ye.

我明白这是说我需要按顺序订购,但问题是我按年范围订购。

EN

回答 3

Stack Overflow用户

发布于 2018-07-08 09:28:32

错误:只有当您有一个或多个聚合列(如sum、max、min、avg)并且需要在GROUP BY子句中添加所有其他列时,才需要使用GROUP BY子句。

您尝试过的内容:交叉连接所有的书籍和所有作者,并显示一个大的结果集。我假设图书的author_id在表书的pub_id列中,id在author.au_id中。如果不使用INNER JOIN ...,则可以将联接条件放入WHERE语句:WHERE author.au_id=book.pub_id and year >= 1990 and year <= 1993中。

票数 0
EN

Stack Overflow用户

发布于 2018-07-08 09:54:34

在对两个表进行查询时,请使用“”引用特定的表。当你得到一个错误

错误:"author.last_name“列必须出现在GROUP子句中

在group by语句中也包括author.last_name,就像我在下面的代码中包含了Author_name一样。

代码语言:javascript
复制
select concat(author.last_name, ',', author.first_name) as 
Author_name,book.title,book.year
from author,book
where book.year >= 1990 and book.year <= 1993
group by book.year,book.title,Author_name
order by book.year asc;
票数 0
EN

Stack Overflow用户

发布于 2018-07-08 11:43:28

您所拥有的两个表不足以回答这个问题。你需要一个连接表,每一位作者和一本书都有一行。让我把这叫做book_authors

然后,将此查询编写为:

代码语言:javascript
复制
select concat(a.last_name, ',', a.first_name) as name, b.title, b.year
from author a join
     book_authors ba
     on a.au_id = ba.au_id join
     book b
     on b.isbn = ba.isbn
where b.year >= 1990 and b.year <= 1993 
order by b.year;

备注:

  • 不要在FROM子句中使用逗号。始终使用正确、显式、标准的 JOIN语法。如果2018年的一堂课在教过时的语法,那是非常非常可悲的。
  • 此查询似乎不需要GROUP BY
  • 使用表名的缩写表别名。
  • 限定所有列引用(也就是说,在引用中包括表名)。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51228698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档