按属性和计数分组,postgreSQL

Grouping by attributes and counting, postgreSQL

我编写了以下代码来计算 book_id 在 table 出售的图书中有多少个实例。

    SELECT book_id, sum(counter) AS no_of_books_sold, sum(retail_price) AS generated_revenue
    FROM(
        SELECT  book_id,1 AS counter, retail_price
        FROM shipments 
        LEFT JOIN editions ON (shipments.isbn = editions.isbn)
        LEFT JOIN stock ON (shipments.isbn = stock.isbn)
        ) AS soldBooks
    GROUP BY book_id

如您所见,我使用了 "counter" 来解决我的问题。但我确信必须有更好、更内置的方式来实现相同的结果!必须有某种方法可以按给定属性将 table 组合在一起,并创建一个新列来显示每个属性的计数。有人可以与我分享这个吗?

谢谢!

SELECT book_id, 
       COUNT(book_id) AS no_books_sold, 
       SUM(retail_price) AS gen_rev
  FROM shipments 
         JOIN editions ON (shipments.isbn=editions.isbn)
         JOIN stock ON (shipments.isbn=stock.isbn)
 GROUP BY book_id