我想创建一个查询,用于计算具有相同标题的可用图书的数量

时间:2016-01-21 15:28:20

标签: sql group-by

我想创建一个查询,用于计算具有相同标题的可用图书的数量。我的桌子看起来像这样

Book_ID |  Book_Title |  Author | status
-----------------------------------------------------------------
122334  |  Title11111 |  allann  | available
839661  |  Title12222 |  reddd   | available
839373  |  Title11111 |  allann  | not_avail

我希望它看起来像这样:

Book_Title |  Author | Avail_Copies | TotalCopies
-----------------------------------------------------------------------------
Title11111 |  allann  |  1          | 2

Title12222 |  reddd   |  1          | 1

3 个答案:

答案 0 :(得分:0)

尝试使用子查询来解决您的任务

SELECT DISTINCT A.book_Title,
        A.Author,
        (SELECT COUNT(*) FROM Table AS A2
         WHERE A2.book_title = A.book_title
                AND A2.status = 'available') as avail_copies,
        (SELECT COUNT(*) FROM Table AS A2
         WHERE A2.book_title = A.book_title') as total_copies,  
FROM Table AS A

答案 1 :(得分:0)

您可以使用SUM()

进行简单的CASE汇总
Select  Book_Title, Author,
        Sum(Case When status = 'available' Then 1 Else 0 End) As Avail_Copies,
        Count(*) As TotalCopies
From    BookTable
Group By Book_Title, Author

SQLFiddle Demo

答案 2 :(得分:0)

选择Book_Title,作者,SUM(IF(状态='可用',1,0))作为Avail_Copies,COUNT(Book_ID)作为TotalCopies FROM books GROUP BY Book_Title,作者;