0

I am trying to get this table to display book num, book title, and the number of times each book was checked out (even if it was never checked out.)

The current output I get is correct, but I want to sort it by book num and "Times Checked Out".

SELECT book.book_num
  ,book_title
  ,Count(checkout.book_num) AS "Times Checked Out"
FROM checkout right join book ON checkout.book_num = book.book_num
GROUP BY book.book_num, book_title;
4

4 回答 4

1

您也可以将其用作内部查询:

SELECT * FROM (
    SELECT book.book_num,book_title,Count(checkout.book_num) AS "Times Checked Out"
    FROM checkout right join book ON checkout.book_num = book.book_num
    GROUP BY book.book_num, book_title
) AS foo
ORDER BY "Times Checked Out";
于 2013-11-07T19:47:45.310 回答
0

最简单的方法是将其设置为子查询并对其进行排序:

SELECT book_num AS "Book Number",
 ,book_title AS "Book Title"
 ,times_checked_out AS "Times Checked Out"
FROM (
    SELECT Book.book_num
      ,Book.book_title
      ,COUNT(Checkout.book_num) AS times_checked_out
    FROM checkout Checkout
    RIGHT OUTER JOIN book Book ON Checkout.book_num = Book.book_num
    GROUP BY Book.book_num, Book.book_title
) Counts
ORDER BY book_num,times_checked_out

这只会做COUNT一次并提供您正在寻找的订购。它也符合 ANSI,因此非常高效。

于 2013-11-07T19:47:16.590 回答
0
SELECT
    book.book_num,
    book_title,
    COUNT(checkout.book_num) AS "Times Checked Out"
FROM checkout
RIGHT JOIN book ON checkout.book_num = book.book_num 
GROUP BY
    book.book_num,
    book_title
ORDER BY
    book.book_num,
    COUNT(checkout.book_num);
于 2013-11-07T19:44:41.923 回答
0

使用公用表表达式

;WITH BookDetails AS
(
    SELECT book.book_num
          ,book_title
          ,Count(checkout.book_num) AS "TimesCheckedOut"
    FROM checkout right join book ON checkout.book_num = book.book_num
    GROUP BY book.book_num, book_title;
)

SELECT
    book_num
   ,book_title
   ,TimesCheckedOut as 'Times Checked Out'
FROM BookDetails
ORDER BY TimesCheckedOut

这是假设您没有使用 MySql 而是使用 MSSQL 之类的东西

于 2013-11-07T19:45:58.930 回答