首页 > 解决方案 > 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 的情况下加入它们,请帮助大家

标签: sqldatabase

解决方案


这是一种解决方案(在 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 秒的差异)。根据需要进行调整。我还假设(根据您的示例)订单总是在收据之前。


推荐阅读