SQL - 如果所有'count case when'语句返回0,则不显示结果

时间:2016-04-12 08:52:29

标签: sql sql-server tsql count null

我有一个SQL语句有多个'count case when'语句我的问题是我不想显示结果所有结果都是null

如果源描述为所有四个count语句返回null,我不想显示源描述行。我被困住了,不知道如何实现这一目标

任何建议都将不胜感激

这是我的sql

SELECT CASE WHEN CHARINDEX('**-**', SourceDescription) > 0 then 
SourceDescription
WHEN CHARINDEX('-', SourceDescription) > 0 THEN
LEFT(SourceDescription, CHARINDEX('-', SourceDescription)-1) else
SourceDescription END as 'Source',

count(case when StartDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0)    THEN 1 ELSE NULL END) as 'Total',
count (case when CompletionDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0) THEN 1 ELSE NULL END)as 'Completed',
count (case when ClosedDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0) and CompletionDate is null then 1 ELSE null END)as 'Closed',
count (case when ExchangeDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0)then 1 else NULL END)as 'Exchanged'

from 
CASE_record with (nolock)
inner join case_warehouse  with (nolock)  on CASE_record.casekey = case_warehouse.casekey
WHERE  TypeCode = 'b'

group by CASE WHEN CHARINDEX('**-**', SourceDescription) > 0 then 
SourceDescription
WHEN CHARINDEX('-',SourceDescription) > 0 THEN
LEFT(SourceDescription, CHARINDEX('-', SourceDescription)-1) else
SourceDescription END

1 个答案:

答案 0 :(得分:1)

您可以在where子句中包含每个谓词,以确保只返回与至少一个条件匹配的记录:

WHERE   TypeCode = 'b'
AND (   StartDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0)
    OR  CompletionDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0)
    OR  (ClosedDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0) AND CompletionDate IS NULL)
    OR  ExchangeDate = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) - 1, 0)
    )