开发者

Always select a row sql

开发者 https://www.devze.com 2023-03-26 17:42 出处:网络
I have a case statment (see below) but I always want to return a value even if nothing matches the WHERE clase. Is that possible? Thanks

I have a case statment (see below) but I always want to return a value even if nothing matches the WHERE clase. Is that possible? Thanks

SELECT 
    CASE 
        WHEN COUNT(*) > 10 THEN 1
        ELSE 0
    END
FROM 
fldt_QueryDSLAM lastDay
WHERE AccountID = @acc
    AND lastDay.DSL 开发者_StackOverflow中文版= @dsl
GROUP BY lastDay.DSL


If the WHERE clause returns one row (or one group more precisely), remove the GROUP BY. Then you'll always have one row in the output.

I assume it will (return one group) because you have GROUP BY on a filter column, and AccountID isn't mentioned in either SELECT or GROOUP BY

SELECT 
    CASE 
        WHEN COUNT(*) > 10 THEN 1
        ELSE 0
    END
FROM 
    fldt_QueryDSLAM lastDay
WHERE
    AccountID = @acc AND lastDay.DSL = @dsl

For why, see this: Does COUNT(*) always return a result?


You can wrap the select within an isnull;

SELECT ISNULL((
    SELECT 
        CASE 
            WHEN COUNT(*) > 10 THEN 1
            ELSE 0
        END
    FROM 
    fldt_QueryDSLAM lastDay
    WHERE AccountID = @acc
        AND lastDay.DSL = @dsl
    GROUP BY lastDay.DSL
), -99 /*no match*/)
0

精彩评论

暂无评论...
验证码 换一张
取 消