我正在尝试列出一年中每个月的数据库中最好的租借书籍。我正在尝试列出最多10本书,并列出最多的租金,例如
目前它是随机输出但按月分组。我将附上我的架构以及我的查询。
查询
USE data_mart;
SELECT bookId, book_name, COUNT(*) AS 'Rental Count', month(rental_date) as 'Month'
FROM fact_rental
GROUP BY month(rental_date), bookId
ORDER BY month(rental_date) DESC;
模式
CREATE TABLE fact_rental (
rental_id INT(8) UNSIGNED AUTO_INCREMENT,
cardNo int(11) NOT NULL,
borrower_fname varchar(45) DEFAULT NULL,
borrower_lname varchar(45) DEFAULT NULL,
staffNo int(11) NOT NULL,
staff_fname varchar(45) DEFAULT NULL,
staff_lname varchar(45) DEFAULT NULL,
branchId int(11) NOT NULL,
branchName varchar(45) DEFAULT NULL,
bookId int(11) NOT NULL,
book_name varchar(45) DEFAULT NULL,
rental_date DATETIME,
return_date DATETIME DEFAULT NULL,
count_returns INTEGER(10) DEFAULT 1,
count_rentals INTEGER(8) UNSIGNED DEFAULT 1,
FOREIGN KEY (staffNo) REFERENCES dim_staff(staffNo),
FOREIGN KEY (branchId) REFERENCES dim_library_branch(branchId),
FOREIGN KEY (cardNo) REFERENCES dim_borrower(cardNo),
FOREIGN KEY (bookId) REFERENCES dim_book(bookId),
PRIMARY KEY (rental_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
答案 0 :(得分:0)
你似乎想要:
SELECT bookId, book_name, COUNT(*) AS RentalCount, month(rental_date) as Month
FROM fact_rental
GROUP BY month(rental_date), bookId
ORDER BY RentalCount DESC
LIMIT 10;
答案 1 :(得分:0)
对于前10个你可以使用限制10
USE data_mart;
SELECT bookId, book_name, COUNT(*) AS 'Rental Count', month(rental_date) as 'Month'
FROM fact_rental
GROUP BY month(rental_date), bookId
ORDER BY month(rental_date) DESC limit 10;
但事实上几个月是递归的..你应该检查(或过滤)一年,例如:
USE data_mart;
SELECT bookId, book_name, COUNT(*) AS 'Rental Count', month(rental_date) as 'Month'
FROM fact_rental
GROUP BY month(rental_date), bookId
where year(rental_date) = 2017
ORDER BY month(rental_date) DESC limit 10;
答案 2 :(得分:0)
可能有一种方法,但如果数据集很大,它可能会使数据库服务器崩溃。这个很不理想,但有一个12件UNION
你可以得到想要的结果(我按月过滤了一年):
(SELECT bookId, book_name, COUNT(*) AS rental_count, DATE_FORMAT(rental_date, '%M') as rental_month FROM fact_rental WHERE date_format(rental_date, '%Y-%m') = '2017-10' GROUP BY bookId ORDER BY rental_count DESC LIMIT 10)
UNION ALL
(SELECT bookId, book_name, COUNT(*) AS rental_count, DATE_FORMAT(rental_date, '%M') as rental_month FROM fact_rental WHERE date_format(rental_date, '%Y-%m') = '2017-09' GROUP BY bookId ORDER BY rental_count DESC LIMIT 10)
UNION ALL
(...)