Sql 查询可用图书数和总图书数

Sql Query for number of available and total books

I need a query which will return list of book from book table

but it will show total number of books and books available too ..

对于图书数量,它将计算具有类似 ISBN 的图书数量 n amount count 这将计算具有类似 ISBN 且状态可用的图书数量

Table结构

Bookid booktitle author ISBN edition publisher price supplier volume language status

status contains available,issued

我想要结果

BookTitle Author Publisher Location Total available

还请解释查询,因为我需要在很多表上实现它

到目前为止我试过的查询

select *,count(1) as Quantity from Book group  by Book.BookTitle

成功给了我总数量的书单

select *,count(1) as Quantity from Book where status='Available' group  by Book.BookTitle

它成功地给了我有多少可用的书籍列表。

但我需要总量和可用量的组合..

您必须按 SELECT 查询中的所有项目分组。您可以计数 (*) 或求和 (1)。这是我的做法:

SELECT BookId, Name, Available, count(*) as Quantity
FROM Book GROUP BY Bookid,Name,Available

简而言之:

select isbn, booktitle, sum(case when status='available' then 1 else 0 end) as avail, count(*) as total
from Book
group by isbn, booktitle

http://sqlfiddle.com/#!2/80a41/5

我绝对建议你阅读第三范式

select d.* from (select BookTitle,Author,Publisher,Location,count(BookTitle) as Total, Status, Count(Status) as StatusQuantity from Book group by BookTitle,Author,Publisher,Location,Status)d where d.Status='Available'

试试这个:

SELECT 
     BookTitle,
     Author,
     Publisher,
     Location, 
     SUM(CASE WHEN status='available' THEN 1 ELSE 0 END) Available,
     COUNT(*) AS Total
FROM Book
GROUP BY BookTitle,Author,Publisher,Location

你有什么关键限制吗??
你必须拆分 table..
使用 bookid 或 ISBN 作为 主键 ,将状态存储在单独的 table..
进一步处理将很容易,否则记录应该是多余的..