SQL中的GROUP BY

时间:2016-10-25 06:50:44

标签: sql sql-server

我从以下流程图创建了一个数据库:https://www.learncodinganywhere.com/learningmanagementsystem/links/07_DB/SQL_Drill.pdf

如果我试图找到每个Library_Branch.BranchName中某个书名的副本数量,我会用什么方法来做?我知道如果我想获得每个分支中所有副本的数量,我可以这样做:

SELECT sum(No_Of_Copies) as 'Total Copies' 
FROM BOOK_COPIES 
WHERE BookId in (select BookId 
                 from book where title like '%The Great Gatsby%')

但我无法弄清楚如何区分每个分支和副本数量。如果可能,请不要直接回答!

试图通过我自己来解决这个问题,只需要一点点指导。 编辑:这越来越近了吗?我觉得好像我几乎就在那里。

     SELECT sum(No_Of_Copies) as 'Total Copies' FROM BOOK_COPIES
        WHERE BookId in 
        (
        select BookId 
        from book where title like 
        '%The Great Gatsby%'
        ) Group By BranchName in
        (
        SELECT BranchName
        from LIBRARY_BRANCH
        )

2 个答案:

答案 0 :(得分:0)

select lb.BranchName, b.Title, sum(bc.no_of_copies) 
    from Library_Branch lb
    join Book_Copies bc
    on lb.BranchId = bc.BranchId
    join Books b
    on bc.BookId = b.BookId
    group by lb.BranchName, b.Title

答案 1 :(得分:0)

SELECT Branch, title, sum(No_Of_Copies) as 'Total Copies' 
FROM BOOK_COPIES 
INNER JOIN BOOK
ON Book_Copies.BOOkID = Book.BOOKID
LEFT OUTER JOIN Branch
ON Branch.BranchID = BOOK_Copies.BranchID
WHERE Book.title like '%The Great Gatsby%'
GROUP BY Branch, Title