我编写了一个视图,根据符合条件的现有文档数显示值。如果该数字大于1,则为“是”。否则'不'。
这是我的SQL:
with docStatus as
(
select c.PersonID, d.Status as dStatus, d.Source as Source, count(d.Status) as rDoc
from Documents d with (nolock)
inner join PersonDocuments d1 with (nolock) on d1.DocumentID = d.DocumentID
inner join Person c with (nolock) on c.PersonID = d1.PersonID
group by c.PersonID, d.Status, d.Source
)
select distinct(
case
when rDoc > 1 then 'Yes'
else 'No'
end ) as MissingDocuments,
docStatus.PersonID
from docStatus
where dStatus = 12
and Source in (2, 3, 9, 11)
order by docStatus.PersonID
当我运行整个查询时(使用select *
而不是distinct
),这就是它的样子:
由于行的值为rDoc
,因此使用disticnt
运行时的输出会重复列出的行。这是有道理的:
问题
如果任何行包含rDoc
值> 1它返回单行的“是”值,而不是一行“是”而一行“否”?如果rDoc
>不存在其他行,我仍然需要'否'值1。
答案 0 :(得分:2)
使用group by
和一些条件逻辑:
select PersonID,
(case when max(rDoc) > 1 then 'Yes'
else 'No'
end) as MissingDocuments
from docStatus
where dStatus = 12 and Source in (2, 3, 9, 11)
group by PersonId
order by PersonID;
我应该注意,这假定rDoc
不是NULL
。如果某人的所有值均为NULL
,则会出现问题。如果你知道逻辑应该是什么(在这种情况下上面会返回'No'
),这很容易修复。