在文档审阅工具中,可以创建"批次"的文件。批处理是一组相关文档,由GroupID标识。
这些文档组将提供给审阅者,审阅者更新名为Testcompleted的字段。该字段有3种可能的状态:1,0或null。组中的文档数量各不相同。
在下面的示例中,我有3组("批次")文档。例如,第一批(batch_0001)有2个文件(58和59)。
#Document
ArtifactID Testcompleted GroupID
--------------------------------------
58 1 4
59 1 4
60 null 6
61 1 6
62 null 7
63 null 7
64 null 7
#DocumentBatch
BatchArtifactID DocumentArtifactID
-------------------------------------
66 58
66 59
67 60
67 61
68 62
68 63
68 64
#Batch
ArtifactID Name
------------------------
66 batch_0001
67 batch_0002
68 batch_0003
我需要知道批处理何时完成 - 即:当该批处理中的所有文档都将Testcompleted字段设置为1.在示例中,这是batch_0001的情况。
我正在寻找的输出是:
batch documents reviewed completed
------------------------------------------------------
batch_0001 2 2 yes
batch_0002 2 1 no
batch_0003 3 0 no
我开始加入表格:
select
*
from
#Document d
left join #DocumentBatch db
on db.DocumentArtifactID = b.ArtifactID
left join #Batch b
on db.BatchArtifactID = b.ArtifactID
where
d.Testcompleted = 1
;
这显然不会返回我需要的结果,但我被卡住了。如何解决这个问题的一些帮助将非常感激。
答案 0 :(得分:2)
您可以尝试这样的事情:
select b.name
, count(*) as documents
, sum(d.Testcompleted) as reviewed
, (case when count(*) = sum(d.Testcompleted) then 'yes' else 'no' end) as completed
from [#Document] d
join [#DocumentBatch] db on db.DocumentArtifactID = d.ArtifactID
join [#Batch] b on db.BatchArtifactID = b.ArtifactID
group by b.name
count(*)
包括计算所有值; sum(d.Testcompleted)
仅计算Testcompleted
为1
; 答案 1 :(得分:2)
您想要的是聚合,因此您需要group by
。像这样:
select b.name as batchname, count(d.ARtifactID) as numdocuments,
sum(case when d.testCompleted = 1 then 1 else 0 end) as NumCompleted,
(case when sum(case when d.testCompleted = 1 then 0 else 1 end) > 0
then 'No'
else 'Yes'
end) as AllCompleted
from #Batch b left join
#DocumentBatch db
on db.BatchArtifactID = b.ArtifactID
#Document d left join
on db.DocumentArtifactID = b.ArtifactID left join
group by b.name;
我认为不需要外连接。您应该可以使用inner join
,除非有批次没有文档。如果您确实使用外部联接,则从#Batch
开始比#Document
更有意义,因为您在批次级别聚合。
答案 2 :(得分:2)
select
b.name,
count(db.DocumentArtifactID) as documents,
-- count only completed
count(case when d.Testcompleted = 1 then d.ArtifactID end) as reviewed,
-- if the minimum = 1 there's no 0 or NULL
case when min(cast(Testcompleted as tinyint)) = 1 then 'yes' else 'no' end as completed
from
#Batch b
left join #DocumentBatch db
on db.BatchArtifactID = b.ArtifactID
left join #Document d
on db.DocumentArtifactID = d.ArtifactID
group by b.name;
如果没有丢失的行,您可以切换到内部联接...