我想实现一个存储下限,上限和颜色的SQL表。然后为特定颜色定义不同的范围。
目的是查找值是否落在某个范围内,然后确定颜色。
如何在不存在任何数值范围差距的情况下实现这一目标?
答案 0 :(得分:0)
关于需求和您的实现的细节不是很多,但是我想您可以使用以下想法:
表定义:
CREATE TABLE [dbo].[ColorRanges](
[Id] [int] IDENTITY(1,1) NOT NULL,
[RangeFrom] [int] NULL,
[RangeTo] [int] NULL,
[Color] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_ColorRanges] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
样本数据:
INSERT INTO [ColorRanges] (RangeFrom, RangeTo, Color)
VALUES (NULL, 0, 'Green'),
(0, 100, 'Yellow'),
(100, 200, 'Orange'),
(200, NULL, 'Red')
假设是可能存在无限范围-范围值限制为NULL
。
第二个假设是范围可能重叠-如果您的要求不同,则可以轻松地对其进行调整。
然后为指定值选择颜色是:
DECLARE @Value int
SET @Value = 100
SELECT Color
FROM ColorRanges
WHERE (RangeFrom IS NULL AND RangeTo IS NULL) OR -- that scenario might be not valid
(RangeFrom IS NULL AND @Value <= RangeTo) OR
(@Value BETWEEN RangeFrom AND RangeTo) OR
(@Value >= RangeFrom AND RangeTo IS NULL)