在表格中搜索值

时间:2014-05-12 05:50:45

标签: sql tsql search

我们有一个名为" @ Weight"和我的表中的这个值:

RouteFrom   RouteTo normal      minimum     BP      Q   Value   Price
SYZ         THR     11000.00    99000.00    9.00    100 81.50   9000.00
SYZ         THR     11000.00    99000.00    9.00    250 219.20  7900.00

我想要来自这些值的单个结果,如果@weight&lt; = breakpoint然后只显示一个最小值:99000,如果@weight大于断点且小于Value字段的min,则只显示一个正常值,否则,如果在Qs和Values之一之间的@weight然后显示它自己的价格,如果小于它们并且大于前一行显示前一行价格,最后如果大于每个值并且表中的qs显示更大的价格。< / p> 像这样:

DECLARE @Weight decimal(18,2);
set @Weight = 8;      Price : 99000.00
set @Weight = 10;    Price : 11000.00
set @Weight = 81;    Price : 11000.00
set @Weight = 82;    Price : 9000.00
set @Weight = 150;  Price : 9000.00
set @Weight = 220;  Price : 7900.00
set @Weight = 270;  Price : 7900.00

我写了一些查询,但结果显示错误:(

DECLARE @from nvarchar(3);
DECLARE @to   nvarchar(3);

set @from = 'SYZ';
set @to = 'THR';

DECLARE @Weight decimal(18,2);
set @Weight = 220;

select  case
            WHEN @Weight <= BP   then minimum
            when @Weight < value then Normal
            when @Weight >= value AND  @weight <= Q then Price
            WHEN @weight >= Value AND  @Weight >  Q then Price
        end as 'Price'
from    Waybill.RoutePrices inner join Waybill.RoutePriceQ on Waybill.RoutePrices.Id = Waybill.RoutePriceQ.RoutePriceId
where   RouteFrom = @from and routeTo = @to

我想,我不知道如何使用:case - end statement 当我设置@weight = 220结果多于一个时它们是:9000.00, 7900.00 只是第二个值是正确的(7900.00) 或者当我设置@weight = 150时,结果是: 9000.00 ,11000.00只是第一个是正确的(9000.00)

1 个答案:

答案 0 :(得分:0)

根据你的意见 - 这是你的事吗?

;WITH CTE AS (
select  case
            WHEN @Weight <= BP   then minimum
            when @Weight < value then Normal
            when @Weight >= value AND  @weight <= Q then Price
            WHEN @weight >= Value AND  @Weight >  Q then Price
        end as 'Price'
from    Waybill.RoutePrices inner join Waybill.RoutePriceQ on Waybill.RoutePrices.Id = Waybill.RoutePriceQ.RoutePriceId
where   RouteFrom = @from and routeTo = @to
)
SELECT TOP 1 *
FROM CTE 
ORDER BY Price

我仍然不确定这是否是您的请求,如果是 - 它可以通过许多其他方式解决,可以更加动态地解决,以使用某些GROUP BY或多个GROUP BY提供多个路线和权重的结果PARTITION BY logic