作为一种替代方法,请记住,可以对“简单”CASE 语句的输入值进行数学运算。为此,我经常使用 ROUND,如下所示:
SELECT
CASE ROUND(X, -2, 1)
WHEN 0 THEN 'b' -- 0-99
WHEN 100 THEN 'c' -- 100-199
ELSE 'a' -- 200+
END
由于您的示例包括正负开放式范围,因此这种方法可能不适合您。
还有另一种方法:如果您只考虑 SELECT 语句中的可读性,您可以编写一个标量值函数来隐藏所有混乱:
CREATE FUNCTION dbo.ufn_SortValuesIntoBuckets (@inputValue INT) RETURNS VARCHAR(10) AS
BEGIN
DECLARE @outputValue VARCHAR(10);
SELECT @outputValue =
CASE WHEN @inputValue < 0 THEN 'a'
WHEN @inputValue BETWEEN 0 AND 100 THEN 'b'
WHEN @inputValue > 100 THEN 'c'
END;
RETURN @outputValue;
END;
GO
所以现在你的 SELECT 语句就是:
SELECT dbo.ufn_SortValuesIntoBuckets(X);
One final consideration: I have often found, during benchmark testing, that the "searched" form (which you are trying to avoid) actually has better performance than the "simple" form, depending how many CASEs you have. So if performance is a consideration, it might be worth your while to do a little benchmarking before you change things around too much.