SQL Server Find row with closest value down

mklgxw1f  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(73)

I have a shipping cost table with two dimensions: Zone and Weight . Zone is an exact value. Weight is a range where given value is lower inclusive one. That means that in the given example, the highest range is 200-∞.

I am looking for a cost for given Zone and Weight .

SELECT TOP 1 *
FROM fg.CostTest
WHERE Zone = 'A' AND Weight <= 123
ORDER BY Weight DESC

Having dozens of thousands rows in a table, is there a better way in terms of performance to achieve that?

I am using SQL Server 2022.

huwehgph

huwehgph1#

this might help :

select * from (
   select *, row_number() over (order by abs(weight - 123)) rn
   from fg.CostTest
   where zone = 'A'
) t where rn = 1
pieyvz9o

pieyvz9o2#

I suggest making sure your columns zone and weight has index which would definitely help in the performance.

Then if the table is going to be used several times in queries or stored procedures, it’s best to create an indexed view that contains the LowerBoundWeight and Weight, and then use that view in queries as a join.

The View would be similar to the below:

CREATE VIEW vw_CostTest
AS
SELECT *, LAG(Weight,1,0) OVER (partition by Zone ORDER BY Weight) LowerBoundWeight
FROM CostTest;

Then on the select, join it as such

SELECT [COLUMNA_Names]
FROM Table1 t1
    JOIN vw_CostTest ct on t1.zone=ct.zone 
        AND t1.weight > ct.LowerBoundWeight
        AND t1.weight <= ct.weight
4sup72z8

4sup72z83#

Create procedure, it will help for repetition query :

Step 1 :

Create PROCEDURE [dbo].[FindCost]
 @Zone char(1),
 @Weight int
AS
BEGIN
 SET NOCOUNT ON;
 SELECT Top 1 *
 FROM costtest
 WHERE Zone = @Zone 
 AND Weight <= @Weight
ORDER BY Weight DESC

Step 2: Try the store procedure

Exec FindCost 'A',123

相关问题