【问题标题】:PSQL aggregate functionPSQL 聚合函数
【发布时间】:2018-07-08 03:52:24
【问题描述】:

我在大学里上 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 年(含)出版的所有书籍的作者姓名、书名和出版年份。将作者姓名显示为 Last, First(中间有逗号和空格)。按出版年份对输出进行排序。

输出:

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) 作为 name, title, ye...

我知道它说我需要按顺序排列,但问题要求我按年份范围订购。

【问题讨论】:

  • 你为什么还要使用GROUP BY?我看不出有必要。但是您缺少authorbook 之间的连接条件。而且您可能更应该使用显式的author INNER JOIN book ON ... 语法——更容易阅读、更容易理解并且错误会很明显。
  • @stickybit 我使用的是GROUP BY,因为到目前为止我们在课堂上所做的一切都让我相信这是必要的。我们还没有涵盖INNER JOIN,所以我不确定它是否适用于这个问题(你不可能知道)。我取下了GROUP BY,终端现在挂了:select concat(last_name, ',', first_name) as name, title, year from author, book where year &gt;= 1990 and year &lt;= 1993 order by year;
  • 没有链接authorbook 的键。你不能用这两个表做你想做的事。

标签: sql postgresql group-by


【解决方案1】:

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

您已经尝试过:将所有书籍与所有作者交叉连接并显示一个大型结果集。 我假设这本书的 author_id 在 table book 的列pub_id 中,并且相同的 id 在 author.au_id 中。 如果不使用INNER JOIN ...,可以将连接条件放在WHEREstatement 中:WHERE author.au_id=book.pub_id and year &gt;= 1990 and year &lt;= 1993

【讨论】:

    【解决方案2】:

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

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

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

    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;
    

    【讨论】:

      【解决方案3】:

      您拥有的两张表不足以回答这个问题。您需要一个联结表,每个作者和每本书有一行。让我称之为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
      • 使用作为表名缩写的表别名。
      • 限定所有列引用(即,在引用中包含表名)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-07
        • 2012-08-07
        • 2014-02-25
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多