Sql 使用GROUP BY从多个表中选择
我对多任务查询有点小问题。(关系数据库管理系统:访问) 以下是数据库模式:(此查询中仅使用S_卡、书籍、作者、学生表) S_卡是学生图书订单(在图书馆) 查询: 选择学生中最受欢迎的作者以及该作者在图书馆订购的书籍数量 虽然我可以在一次查询中获得订单+作者列表,但如下所示:Sql 使用GROUP BY从多个表中选择,sql,ms-access,count,group-by,Sql,Ms Access,Count,Group By,我对多任务查询有点小问题。(关系数据库管理系统:访问) 以下是数据库模式:(此查询中仅使用S_卡、书籍、作者、学生表) S_卡是学生图书订单(在图书馆) 查询: 选择学生中最受欢迎的作者以及该作者在图书馆订购的书籍数量 虽然我可以在一次查询中获得订单+作者列表,但如下所示: SELECT Students.FirstName & " " & Students.LastName AS [Student], Books.Name AS [Book], Autho
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
结果(对不起,是俄语):
我不明白,为什么我不能像这样计数和分组:
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
我得到一个错误,“Authors.FirstName&&&Authors.LastName”不是静态函数或组的一部分
问题:
+
而不是&
。此外,还应按非聚合函数的对象进行分组
SELECT Students.FirstName + ' ' + Students.LastName AS [Student]
, Books.Name AS [Book]
, COUNT(Authors.FirstName + ' ' + Authors.LastName) AS [Number of books]
FROM Students
JOIN S_Cards
ON S_Cards.ID_Student = Students.ID
JOIN BOOKS
ON S_Cards.ID_Book = Books.ID
JOIN Authors
ON Books.ID_Author = Authors.ID
GROUP BY Students.FirstName + ' ' + Students.LastName
, Books.Name
请注意,我已将您的查询更改为标准ANSI join语法,这使得错误更难产生,也更易于阅读
想想看,你的计数似乎有点奇怪。图书的数量不是计数(books.ID)?您必须根据不属于聚合函数的任何内容进行分组:
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 Students.FirstName & " " & Students.LastName,
Books.Name AS [Book]
我建议您开始使用显式连接而不是隐式连接。在大多数情况下,MS Access有更好的选择
<...>
FROM Students
INNER JOIN S_Cards
ON Students.ID = S_Cards.ID_Student
来自学生
内部连接S_卡
关于Students.ID=S_卡。ID_学生
或
来自学生
左加入S_卡
关于Students.ID=S_卡。ID_学生
查询设计窗口将允许您使用正确的语法构建联接。只需将联接字段从一个表拖放到下一个表,然后选择所需的联接类型。解决方案(从中提取):
这假设您使用的是SQL Server(看起来是这样的)。请在将来总是用适当的RDBMS标记问题。谢谢回复。我认为COUNT(Books.ID)会计算某本书的订购次数。我需要数一数作者的书被订购了多少次,而不是某一本书。RDBMS是一种访问。
<...>
FROM Students
LEFT JOIN S_Cards
ON Students.ID = S_Cards.ID_Student
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