gpt4 book ai didi

SQL Join 2个具有日期差异的表

转载 作者:搜寻专家 更新时间:2023-10-30 23:26:40 26 4
gpt4 key购买 nike

我有2张表,一张是订单,一张是收据。我面临的问题是他们没有 UID,唯一可以加入的是日期。问题在于,日期相同,但它们之间的时差约为 30 秒。我的问题是,有什么方法可以加入这两个表吗?

所以,第一个表的格式如下

|   date        | order | price | 
|1/1/13 06:05:32| tea | 3 |
|1/2/13 07:04:24| coffee| 2 |
|4/3/13 13:31:23| tea | 3 |

第二个表格是这个格式

|   date        | order | quantity | 
|1/1/13 06:05:42| tea | 3 |
|1/2/13 07:04:54| coffee| 2 |
|4/3/13 13:31:56| tea | 3 |

我想要的输出是

|   date        | order | quantity |  price | 
|1/1/13 06:05:42| tea | 3 | 3 |
|1/2/13 07:04:54| coffee| 2 | 2 |
|4/3/13 13:31:56| tea | 3 | 3 |

基本上,我的目标是合并这两个表,以便我可以看到它们之间的区别,但我不知道如何在没有唯一 ID 的情况下加入它们,请大家帮忙

最佳答案

这是一种解决方案(在 SQLite3 上尝试过,但如果您替换为相应的日期函数,其他 DBMS 也类似):

create table orders([date],[order],price);
insert into orders values
('2013-01-01 06:05:32', 'tea', 3),
('2013-01-02 07:04:24','coffee',2),
('2013-04-03 13:31:23', 'tea', 3);

create table receipts([date],[order],quantity);
insert into receipts values
('2013-01-01 06:05:42', 'tea', 3),
('2013-01-02 07:04:54','coffee',2),
('2013-04-03 13:31:56', 'tea', 3);

-- My desired output is
--
-- | date | order | quantity | price |
-- |1/1/13 06:05:42| tea | 3 | 3 |
-- |1/2/13 07:04:54| coffee| 2 | 2 |
-- |4/3/13 13:31:56| tea | 3 | 3 |

select r.[date],[order],quantity,price
from orders o join receipts r using([order])
where r.date > o.date
and r.date < datetime(o.date,'+40 seconds')

甚至:

select r.[date],[order],quantity,price
from orders o join receipts r using([order])
where r.date between o.date and datetime(o.date,'+40 seconds')

我用了 40 秒(你说大约 30 秒,但你的示例输出捕获了 33 秒的差异)。根据需要进行调整。我还假设(根据您的示例)订单总是先于收货。

关于SQL Join 2个具有日期差异的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56315287/

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