I've a got a little problem with multitable query. (RDBMS: Access)
Here is the database schema: (only S_Cards, Books, Authors, Students tables are used in this query) S_Cards is Student book order (in library).
Query: Select the most popular author(s) among students and the number of this author's books, which were ordered in library.
Although I can get list of orders + authors like this in one query:
SELECT
Students.FirstName & " " & Students.LastName AS [Student],
Books.Name AS [Book], Authors.FirstName & " " & Authors.LastName AS [Author]
FROM
Students,
Books,
S_Cards,
Authors
WHERE
S_Cards.ID_Student = Students.ID
AND S_Cards.ID_Book = Books.ID
AND Books.ID_Author = Authors.ID
ORDER BY Authors.LastName
Result (sorry, it's in Russian):
I can't figure out, why I can't COUNT and GROUP BY like this:
SELECT
Students.FirstName & " " & Students.LastName AS [Student],
Books.Name AS [Book],
COUNT(Authors.FirstName & " " & Authors.LastName) AS [Number of books]
FROM Students, Books, S_Cards, Authors
WHERE
S_Cards.ID_Student = Students.ID
AND S_Cards.ID_Book = Books.ID
AND Books.ID_Author = Authors.ID
GROUP BY 3
I get an error that 'Authors.FirstName & " " & Authors.LastName' is not a part of static function or group.
Questions:
The GROUP BY clause is used along with some aggregate functions to group columns with the same values in different rows. The group by multiple columns technique retrieves grouped column values from one or more database tables by considering more than one column as grouping criteria.
You cannot write select inside the Group by clause.
Using JOIN in SQL doesn't mean you can only join two tables. You can join 3, 4, or even more! The possibilities are limitless.
Solution (extracted from older revision in question):
SELECT TOP 1 Author, COUNT(Book) AS [Number of books] FROM
(
SELECT
Students.FirstName & " " & Students.LastName AS [Student],
Books.Name AS [Book],
Authors.FirstName & " " & Authors.LastName AS [Author]
FROM
Students,
Books,
S_Cards,
Authors
WHERE
S_Cards.ID_Student = Students.ID AND
S_Cards.ID_Book = Books.ID AND
Books.ID_Author = Authors.ID
ORDER BY Authors.LastName
)
GROUP BY Author
ORDER BY 2 DESC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With