sql - SQL Join 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 秒的差异)。根据需要进行调整。我还假设(根据您的示例)订单总是在收据之前。
推荐阅读
- r - 如何在闪亮的应用程序中显示日志文件内容?
- excel - 平均 3 个值在 1 列中循环?
- elasticsearch - kibana中数据表组件中的动态列
- python - 数组中的元素将数据类型从浮点数更改为字符串
- c# - WPF如何制作一个自定义组合框,里面有一个按钮来清除
- node.js - 如何在 Firebase 后端运行一些脚本?
- php - PHP if 锚标记语句不起作用
- java - 从消费者组中获取 KafkaConsumers 列表
- python - Pandas - 基于每列的前 x% 值,标记为新数字
- python - 将scipy稀疏coo矩阵转换为networkx图并返回不会产生原始矩阵