MSSQL_如何通过循环显示数字的范围?

时间:2015-03-03 00:14:52

标签: sql-server loops

我正在使用MSSQL来运行查询,但我想通过使用循环来简化当前步骤。

-- My current script
select product, price,price_range
from
        (select
                product,
                price,
                case
                         when price <= 100 then 'upto100'
                         when price between 101 and 200 then '101-200'
                         when price between 201 and 300 then '201-300'
                         when price between 301 and 400 then '301-400'
                         when price between 401 and 500 then '401-500'
                         when price between 501 and 600 then '501-600'
                         when price between 601 and 700 then '601-700'
                         when price between 701 and 800 then '701-800'
                         when price >= 801 then '800+EURO'
                end as price_range
        from DATA) as A

现在我的脚本工作了,它按我的意愿返回正确的结果:

product    price     price_range
shoes      50        upto100
clothes    456       401-500
computer   1500      800+EURO

但是,我能简单一点吗?我可以以某种方式使用循环而不是&#39; case ...当...然后&#39 ;?然后,如果价格上涨,我不必写很多案例。&#39;。

我尝试使用&#39;声明&#39;和&#39;而&#39;但没有成功。在这种情况下如何为循环设置变量?

1 个答案:

答案 0 :(得分:1)

你不能比这简单得多。最简单的事情是创建一个具有价格范围的表并加入它而不是在查询中对其进行硬编码。如果在多个地方使用此查询,或者经常使用此查询,则应该这样做。

类似的东西:

CREATE TABLE price_ranges (
   lowest INT,
   highest INT,
   name VARCHAR
)

INSERT INTO price_ranges VALUES (
   (NULL, 100, 'upto100'),
   (101, 201, '101-200),
   ...
   (801, NULL, '801+EURO')
)

SELECT DATA.product, DATA.price, RANGES.name AS price_range
   FROM DATA, 
        price_ranges RANGES
   WHERE (DATA.price >= RANGES.lowest  OR RANGES.lowest IS NULL)
     AND (DATA.price <= RANGES.highest OR RANGES.highest IS NULL)
AS A