1

运行 SQL Server 2012

我有一个查询,计算已签出一本书的客户数量。它还计算了两次检查同一本书的人。所有这些都添加到一个列Customers Checked Out.中 问题是我不希望它计算那些已经多次签出该书的人。

例如,

Book Title                  Customers Checked OUt 
Title of Book1                         2
Title of Book2                         3
TItle of Book3                         1

在这种情况下,书 1 的标题实际上只签出了一个,但签出了两次。我怎样才能让它说 1 次而不是 2

添加查询

SELECT 
    Book.title AS 'Title of Book', 
    COUNT(Book_Rental.Book_id) AS 'Customers Checked Out'
FROM Book
JOIN Book_Rental ON Book.Book_id = Book_Rental.Book_id
JOIN Customer ON Book_Rental.Customer_id = Customer.customer_id
GROUP BY Book.Title
ORDER BY [# of Customers Rented] DESC;
4

1 回答 1

2

据推测,您的查询类似于:

select BookTitle, count(*)
from CheckOuts
group by BookTitle

您想将 更改count()count(distinct)

select BookTitle, count(distinct customerId)
from CheckOuts
group by BookTitle

由于您提供了查询,我认为这就是您想要的:

SELECT Book.title AS 'Title of Book', 
       COUNT(distinct Book_Rental.Customer_id) AS 'Customers Checked Out'
FROM Book
JOIN Book_Rental ON Book.Book_id = Book_Rental.Book_id
JOIN Customer ON Book_Rental.Customer_id = Customer.customer_id
GROUP BY Book.Title
ORDER BY [# of Customers Rented] DESC;
于 2013-04-21T19:49:52.613 回答