SQL Server-获得大于特定值的最接近值

时间:2018-12-07 19:04:14

标签: sql-server match

我有一张表格,其中包含每个订单的到达时间。

Order_arrival_time

order_id   arrival_time
    1               120
    2               239
    3               500           
    ...

对于每个特定的订单,有许多卡车的降级时间可供选择,可以从下表中进行查询:

卡车出发时间

Order_id     Truck_id           deppature_time
 1            truck_0             66
 1            truck_1             125
 1            truck_2             300
 1            truck_3             720
 1            truck_4             900
 1            ...

我想在到达时间之后将每个订单与最近的卡车出发时间进行匹配,例如:

order_id   arrival_time    depature_time
    1               120          125
    2               239          300
    3               500          720   
    ...

2 个答案:

答案 0 :(得分:1)

您可以将窗口功能用作

CREATE TABLE T1(
  OrderID INT,
  ArrivalTime INT
);

CREATE TABLE T2(
  OrderID INT,
  TruckID VARCHAR(45),
  DepartureTime INT
);

INSERT INTO T1 VALUES
(1 ,120),
(2 ,239),
(3 ,500);

INSERT INTO T2 VALUES
(1, 'truck_0' , 66),
(1, 'truck_1' , 125),
(1, 'truck_2' , 300),
(2, 'truck_3' , 720),
(2, 'truck_4' , 900);

WITH C AS
(
SELECT T1.OrderID,
       T1.ArrivalTime,
       T2.DepartureTime,
       ROW_NUMBER() OVER(PARTITION BY T2.OrderID ORDER BY T2.DepartureTime) RN
FROM T1 INNER JOIN T2
     ON T1.OrderID = T2.OrderID
)
SELECT OrderID,
       ArrivalTime,
       DepartureTime
FROM C
WHERE RN = 2;

返回:

+---------+-------------+---------------+
| OrderID | ArrivalTime | DepartureTime |
+---------+-------------+---------------+
|       1 |         120 |           125 |
|       2 |         239 |           900 |
+---------+-------------+---------------+

Demo


更新:

SELECT T1.OrderID,
       T1.Arrivaltime,
       TT.DepartureTime
FROM
(
  SELECT T1.OrderID,
         T1.ArrivalTime,
         T2.DepartureTime,
         ROW_NUMBER() OVER(PARTITION BY T2.OrderID ORDER BY T1.OrderID) RN
  FROM T1 CROSS JOIN T2
) TT INNER JOIN T1
ON T1.OrderID = TT.RN - 1;

返回:

+---------+-------------+---------------+
| OrderID | Arrivaltime | DepartureTime |
+---------+-------------+---------------+
|       1 |         120 |           125 |
|       2 |         239 |           300 |
|       3 |         500 |           720 |
+---------+-------------+---------------+

Demo

答案 1 :(得分:0)

通过TOP 1子查询获取departure_time,该子查询具有与arrival_time相关的WHERE子句。

或者,如果您想变得更高级,则可以使用CROSS APPLY。