SQL访谈 - 如果没有记录或计数,如何使用多个表获取记录为零

时间:2014-10-19 11:38:14

标签: sql sql-server database sql-server-2008

我接受了面试,下面是问题。表格如下

表1:Book(BookId是主键)

BookId  | Book_Title  
1       |   Book1  
2       |   Book2  
3       |   Book3  
4       |   Book4  
5       |   Book5

表2:Book_Copies

BookId |    BranchId |  No_of_copies  
1           1           2  
1           2           5  
2           1           0  
2           2           2  
2           3           0  
3           1           0  
3           2           0

输出应列出所有没有库存的书籍,如下所示。

输出

Book_Title
---------
Book3  
Book4  
Book5   

请注意,有两种可能性。 “Book_Copies”表中的“No_of_copies”可以是0或没有Book的记录。
对于例如

  1. “Book3”的总份数为0.输出应该是 包括“Book3”
  2. “Book1和”Book2“的总份数为7和2 分别。 “Book1”和“Book2”都不应显示
  3. “Book_Copies”中没有Book4和Book5的条目,所以两者都有 应该包含在输出中
  4. 回家后,经过这么多试验,我写了下面的查询:)

    select B.Book_Title  
    from  
    (  
      select BC.BookId, sum(BC.No_of_copies) as 'No of copies'  
      from Book_Copies BC  
      group by BC.BookId  
      having sum(BC.No_of_copies) = 0  
      union   
      select B.BookId, BC.No_of_copies  
      from Book B  
      left outer join Book_Copies BC on B.BookId = BC.BookId  
      where BC.BookId is null  
    )  
    as BookIds_withNoStock   
    inner join Book B on B.BookId = BookIds_withNoStock.BookId 
    

    此查询工作正常并经过适当测试 有什么方法可以改进这个查询吗?像复杂性,性能等 如果我们可以改进它,那么如果您可以提供优化的查询和原因会很有帮助。感谢

5 个答案:

答案 0 :(得分:3)

你想要没有股票的书。我会用left outer join,聚合和having子句来处理这个问题:

select b.bookid, b.book_title
from book b left join
     book_copies bc
     on b.bookid = bc.bookid
group by b.bookid, b.book_title
having coalesce(sum(bc.no_of_copies), 0) = 0;

答案 1 :(得分:1)

试试这个

SELECT B.Book_Title
From Book B LEFT JOIN book_copies BC ON B.Bookid = BC.Bookid
Group By B.Book_Title 
Having SUM(ISNULL(BC.no_of_copies,0)) = 0

<强> FIddle Demo

<强>输出:

BOOK_TITLE
Book3
Book4
Book5

答案 2 :(得分:0)

试试这个:

select Book_Title from Book left join Book_Copies on Book.BookId = Book_Copies.BookId 
group by Book_Title having 
 SUM(Book_Copies.No_of_copies) IS NULL OR SUM(Book_Copies.No_of_copies)=0

答案 3 :(得分:0)

以下代码对我有用:

SELECT a.Book_Title 
FROM #books a
    left join(
                SELECT BookId,sum(No_of_copies) Cnt
                FROM #Book_Copies
                GROUP BY BookId) b
        ON a.BookId = b.BookId
WHERE b.cnt = 0 OR b.Cnt is null

答案 4 :(得分:0)

select book_title
from books
where book_id NOT IN 
(
   select book_id
   from book_copies
   group by book_id
   having sum( no_copies) > 0
)