DinShpati
DinShpati

Reputation: 35

Create a VIEW that displays the titles

I need to Create a VIEW

This is what I have so far:

SELECT Book.BookTitle
FROM Book, Borrower, Client
WHERE Book.BookId = Borrower.BookId AND Borrower.ClientId = Client.ClientId AND COUNT(Book.BookId) > 
(SELECT COUNT(Client.ClientId) FROM Client)*0.2
GROUP BY Book.BookTitle
ORDER BY COUNT(Book.BookTitle) DESC;

I keep getting this error: Msg 147, Level 15, State 1, Line 547 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

What am I doing wrong?

Upvotes: 0

Views: 586

Answers (1)

django-unchained
django-unchained

Reputation: 844

I don't think this query is going to give you what you need i.e "display the titles that were borrowed by at least 20% of clients" but I corrected your query syntactically. You can not use aggregate functions in where clause. And group by clause is at incorrect position in your query.

SELECT 
Book.BookTitle, COUNT(Book.BookId)
FROM 
Book 
join Borrower
on Book.BookId = Borrower.BookId
join Client
on Borrower.ClientId = Client.ClientId 
GROUP BY Book.BookTitle
having COUNT(Book.BookId) > 
(SELECT COUNT(Client.ClientId) FROM Client)*0.2
ORDER BY COUNT(Book.BookTitle) DESC;

Upvotes: 1

Related Questions