从SQL中的多表获取记录计数

时间:2013-08-06 08:00:51

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

我有3张桌子,盒子,文件,批次。 每个框包含多个文档,每个文档包含多个批次。 我想在Boxs中选择文档计数,其中文档中至少有一个批处理的值为IsDeleted = 0.

让我们假设该文档有10个批次,如果至少有一个批次具有值isdeleted = 0 我们会计算它,否则如果所有批次都具有isdeleted = 1,我们将不计算它。

如何根据以上内容选择od文档?

我尝试了这个,但它不起作用

SELECT b.ID as BOXID,d.ID as DocID, count(1) as CountDoc 
  FROM Documents as d 
 INNER JOIN dbo.Boxes as b on d.boxid = b.id 
 INNER JOIN dbo.Batches as t on d.ID = t.DocumentID 
 WHERE d.ID = t.DocumentID 
   AND d.boxid= b.id 
   AND t.isDeleted = 0 
 GROUP BY d.ID , t.DocumentID ,b.ID --HAVING t.isDeleted = 0

1 个答案:

答案 0 :(得分:0)

select boxid, count(distinct documentid)
from 
    documents
         inner join batches
    on documents.id = batches.documentid
where
    isdeleted = 0
group by boxid