PSQL聚合函数

时间:2018-07-08 03:52:25

标签: sql postgresql group-by

我在大学里上SQL课,我们正在使用PSQL。

供参考的表。

     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年(包括首尾)的所有书籍的作者姓名,书名和出版年份。将作者姓名显示为姓氏,名字(之间用逗号和空格隔开)。按发布年份对输出进行排序。

输出:

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 BY子句中或在聚合函数中使用   第1行:选择concat(last_name,',',first_name)作为名称,标题,是...

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

3 个答案:

答案 0 :(得分:0)

错误:仅当您有一个或多个聚合列(例如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

答案 1 :(得分:0)

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

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

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

var myAudio = document.createElement('audio');
myAudio.src = 'mySong.mp3';
myAudio.autoplay = true;
myAudio.loop = true;
document.body.appendChild(myAudio);

答案 2 :(得分:0)

您拥有的两个表不足以解决此问题。您需要一个连接表,每位作者和每本书排一行。让我称之为book_authors

然后,此查询将写为:

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
  • 使用表别名的缩写。
  • 限定所有列引用(即在引用中包含表名称)。
相关问题