gpt4 book ai didi

sql - 如何有效地选择小于和大于给定值的最接近值?

转载 作者:行者123 更新时间:2023-12-02 15:35:10 25 4
gpt4 key购买 nike

我有两张表,一张用于值,一张用于位置,我正在尝试插入位置。这些表格已简化为以下内容:

CREATE TABLE value(
Timestamp DATETIME2,
Value float NOT NULL,
PRIMARY KEY(Timestamp)
);

CREATE TABLE location(
Timestamp DATETIME2,
Position INT NOT NULL,
PRIMARY KEY(Timestamp)
);

INSERT INTO value VALUES
('2011/12/1 16:55:01', 1),
('2011/12/1 16:55:02', 5),
('2011/12/1 16:55:05', 10),
('2011/12/1 16:55:08', 6);

INSERT INTO location VALUES
('2011/12/1 16:55:00', 0),
('2011/12/1 16:55:05', 10),
('2011/12/1 16:55:10', 5)

预期结果是

TimeStamp, Value, LowerTime, LowerLocation, UpperTime, UpperLocation
2011-12-01 16:55:01, 1, 2011-12-01 16:55:00, 0, 2011-12-01 16:55:05, 10
2011-12-01 16:55:02, 5, 2011-12-01 16:55:00, 0, 2011-12-01 16:55:05, 10
2011-12-01 16:55:05, 10, 2011-12-01 16:55:05, 10, 2011-12-01 16:55:05, 10
2011-12-01 16:55:08, 6, 2011-12-01 16:55:05, 10, 2011-12-01 16:55:10, 5

(请记住,这是简化的示例数据,用于了解我尝试执行的查询。)

为了进行插值,我需要计算出给定值时间之前和之后的时间和位置。我目前正在使用如下查询来执行此操作:

SELECT 
V.Timestamp,
V.Value,
(SELECT MAX(Timestamp) FROM dbo.location WHERE Timestamp <= V.Timestamp) as LowerTime,
(SELECT TOP 1 Position FROM dbo.location WHERE Timestamp <= V.Timestamp ORDER BY timestamp DESC) as LowerLocation,
(SELECT MIN(Timestamp) FROM dbo.location WHERE Timestamp >= V.Timestamp) as UpperTime,
(SELECT TOP 1 Position FROM dbo.location WHERE Timestamp >= V.Timestamp ORDER BY timestamp ASC) as UpperLocation
FROM
dbo.value V

现在这可以工作了,但这显然需要做很多工作。我想一定是我缺少了一个查询简化,但我整个早上都在玩它,但还没有想出任何具体的东西。希望这里有人有更好的主意。

我目前正在探索是否有办法找出 LowerTime 和 UpperTime 并使用它们来确定位置。像这样的东西:

SELECT 
V.Timestamp,
V.Value,
(SELECT MAX(Timestamp) FROM dbo.location WHERE Timestamp <= V.Timestamp) as LowerTime,
(SELECT Position FROM dbo.location WHERE Timestamp = LowerTime) as LowerLocation,
(SELECT MIN(Timestamp) FROM dbo.location WHERE Timestamp >= V.Timestamp) as UpperTime,
(SELECT Position FROM dbo.location WHERE Timestamp = UpperTime) as UpperLocation
FROM
dbo.value V

但这不起作用。

EDIT1:按照建议更新了查询。但是执行时间没有明显变化。

EDIT2:添加了我对当前正在尝试的方法的想法。

最佳答案

为了简单起见,您至少可以使用 MAX()MIN() 函数来查询 timestamp 字段,而不是 TOP 1 ORDER BY

完整查询将是

SELECT 
V.Timestamp,
V.Value,
(SELECT MAX(Timestamp) FROM dbo.location WHERE Timestamp <= V.Timestamp) as LowerTime,
(SELECT TOP 1 Position FROM dbo.location WHERE Timestamp <= V.Timestamp ORDER BY timestamp DESC) as LowerLocation,
(SELECT MIN(Timestamp) FROM dbo.location WHERE Timestamp >= V.Timestamp) as UpperTime,
(SELECT TOP 1 Position FROM dbo.location WHERE Timestamp >= V.Timestamp ORDER BY timestamp ASC) as UpperLocation
FROM
dbo.value V

关于sql - 如何有效地选择小于和大于给定值的最接近值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8938234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com