总是选择一行sql

时间:2011-08-09 10:04:53

标签: sql sql-server-2008

我有一个case声明(见下文)但我总是希望返回一个值,即使没有任何内容符合WHERE条款。那可能吗?感谢

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

2 个答案:

答案 0 :(得分:2)

如果WHERE子句返回一行(或更准确地说是一个组),则删除GROUP BY。然后,输出中总会有一行。

我认为它会(返回一个组)因为你在过滤列上有GROUP BY,而SELECT或GROOUP BY中没有提到AccountID

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

为什么,请看:Does COUNT(*) always return a result?

答案 1 :(得分:1)

您可以将选择内容包装在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*/)