2015-09-22 93 views
0

我需要幫助解決我的問題。 我有一個值存儲在表中,並且值是一個範圍。SQL Server中的範圍類型參數

例如:

Category    Value 
-------------------- --------------------------- 
1     < 70 
2     > 70 - 90 
3     > 90 - 100 
4     > 100 - 120 
5     > 120 

所以,當我有一個值80,他在第2類

例如:

Value    Category 
-------------------- --------------------------- 
80     2 
75     2 
115     4 
50     1 
99     2 

如何最簡單的方法來存儲這個範圍在表中鍵入參數,並且容易查詢它?

預先感謝您

+0

檢查CASE語句。 https://msdn.microsoft.com/en-us/library/ms181765.aspx和http://www.codeproject.com/Articles/39103/A-Simple-Use-of-SQL-CASE-Expression – Jeremy

+1

**列:**從,到| **查詢:** CASE,BETWEEN, – DarkKnight

+0

可悲的是70不在任何範圍內 – Eric

回答

1

我會這樣設計呢。

CREATE TABLE CategoryRange(
    CategoryId INT IDENTITY(1, 1), 
    MinValue INT NULL, 
    MaxValue INT NULL 
) 

得到相應的類別:

注意範圍被解釋爲value >= min AND value < max

DECLARE @values TABLE(value INT) 
INSERT INTO @values VALUES 
(80), (75), (115), (50), (99) 

SELECT 
    v.value, 
    r.CategoryId 
FROM @values v 
CROSS APPLY(
    SELECT CategoryId 
    FROM CategoryRange 
    WHERE 
     (MinValue IS NULL OR v.value >= MinValue) 
     AND (
      MaxValue IS NULL 
      OR v.value < MaxValue 
     ) 
)r 

SQL Fiddle

| value | CategoryId | 
|-------|------------| 
| 80 |   2 | 
| 75 |   2 | 
| 115 |   4 | 
| 50 |   1 | 
| 99 |   3 | 
+0

真是一個快速的答案!你救了我一天菲利克斯!非常感謝你的幫助。 – user1008497

1

添加到Felix的解決方案,如果範圍是連續的,你可以有範圍表的完美無瑕的設計

-- Accept only one value of range, RangeTo 
DECLARE @ContinuousRange table (CategoryId int identity(1,1), RangeTo int primary key) 
INSERT @ContinuousRange VALUES (70), (90), (100), (120) 
,(2147483647) -- Add this to the last entry for completing the range set 

-- Your table 
DECLARE @Values table (Value int) 
INSERT INTO @Values VALUES (80), (75), (115), (50), (99) 

-- Usage 
SELECT * 
FROM @Values v 
    OUTER APPLY 
    (
     SELECT TOP 1 * FROM @ContinuousRange WHERE v.value <= RangeTo 
     ORDER BY RangeTo 
    ) rng 
1

準備數據

Declare @category as table(categoryid int,fromvalue int, tovalue int) 
Declare @Value as table(value int) 

insert into @category values 
(1,NULL,70 ), 
(2,70 ,90 ), 
(3,90 ,100 ), 
(4,100, 120), 
(5,120,null) 

insert into @Value values 
(80), 
(75), 
(115), 
(50), 
(99) 

查詢

SELECT v.value,c.categoryid 
FROM @category C INNER JOIN @Value V 
      on (v.value >=c.fromvalue or c.fromvalue is null) 
       and (v.value<=c.tovalue or c.tovalue is null)