Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT from multiple tables with GROUP BY

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).

DB Scheme

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):

Query result

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:

  1. Is there a way to do this query without JOIN, only by GROUP BY, SELECT, UNION and how?
  2. What's the problem in my 2nd query?
like image 512
Aremyst Avatar asked Sep 16 '12 13:09

Aremyst


People also ask

Can we use GROUP BY in multiple tables?

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.

Can we use SELECT * with GROUP BY?

You cannot write select inside the Group by clause.

Can you SELECT from 3 tables in SQL?

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.


1 Answers

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
like image 93
2 revs Avatar answered Oct 06 '22 14:10

2 revs