简体   繁体   English

SQL查询-根据数值返回文本

[英]SQL Query - Return Text based on numeric value

I am trying to work out a query where the query will perform a count (total) on a specific column. 我正在尝试制定一个查询,其中该查询将对特定列执行计数(总计)。 If the count is greater than 0, I want to display YES and display NO if the returned count is zero. 如果计数大于0,则我想显示YES,如果返回的计数为零,则显示NO。

So, if I a query as this: 因此,如果我这样查询:

SELECT COUNT(ProblemID)
FROM dbo.ProblemInfo
WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')

that will actually be a subquery, how do I get the subquery to display "YES" when the returned count is greater than 0 and NO if the count is 0? 那实际上将是一个子查询,当返回的计数大于0且计数为0时,如何使子查询显示“ YES”?

I appreciate any insight and help. 感谢您的见解和帮助。

select isnull(
    SELECT MAX('YES')
    FROM dbo.ProblemInfo
    WHERE ProblemID IN (100,101,309,305,205,600,500)
    AND DEPID = '10866'),
'NO')

This is a trick to return either YES if there's at least one matching row, or null if not. 这是一个技巧,如果有至少一个匹配的行,则返回YES ,否则返回null

The wrapping isnull call then turns a null into a NO 包装的非isnull用然后将null转换为NO

try 尝试

SELECT CASE 
WHEN (SELECT COUNT(ProblemID) FROM dbo.ProblemInfo WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')) > 0 
THEN 'YES' 
ELSE 'NO' END 
FROM YourTable

Here's an alternate way of querying that. 这是另一种查询方式。

IF EXISTS(
            SELECT *
            FROM dbo.ProblemInfo
            WHERE (ProblemID IN (100,101,309,305,205,600,500))
            AND (DEPID = '10866')
        )
    BEGIN
        SELECT 'Yes'
    END
ELSE
    BEGIN
        SELECT 'No'
    END

What I like about this method is that, for enormous data-sets, it should be noticeably faster. 我喜欢这种方法的地方在于,对于大量数据集,它应该明显更快。

you can use case when. 您可以在以下情况下使用案例。

SELECT 
case 
when COUNT(ProblemID) = 0 then 'NO'
else 'YES'
end
FROM dbo.ProblemInfo WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM