我编写了以下代码,用于计算soldBooks表中每个book_id的实例数。
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
正如你所看到的,我用了一个"计数器"为了解决我的问题。但我相信必须有一个更好,更内置的方法来实现相同的结果!必须有某种方法通过给定属性将表组合在一起,并创建一个显示EACH属性计数的新列。有人可以跟我分享一下吗?
谢谢!
答案 0 :(得分:1)
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