运行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;
答案 0 :(得分: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;