我试图让这张桌子显示书籍数量,书名,以及每本书被检出的次数(即使它从未被检出过。)
我得到的当前输出是正确的,但我想按书号和“时间检出”对其进行排序。
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;
答案 0 :(得分: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";
答案 1 :(得分: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);
答案 2 :(得分: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
的东西答案 3 :(得分: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标准,非常高效。