SQLITE3:基于时间戳的联接

在我的SQLite3数据库中,我有2个表,一个表带有时间戳和数量,另一个表带有时间戳和比率。问题是“简单”,我需要根据数量和更新的价格来获得良好的价格。

以下是这两个表的示例:

费率表(包含费率的修订,例如,从2012年11月17日到2013年11月16日,费率已更改为58.863 c $,在2013年11月17日再次更改...):

ts                 | cts
------------------------
2010-11-17 00:00:00|58.0
2011-11-17 00:00:00|58.636
2012-11-17 00:00:00|58.863
2013-11-17 00:00:00|59.120
...

生产表(2012年只花了一天时间,但该表到目前为止涵盖了2010年):

ts                 | qty
---------------------------------
...
2012-12-20 07:50:06|130
2012-12-20 08:00:05|130
2012-12-20 08:10:05|120
2012-12-20 08:20:04|130
2012-12-20 08:30:05|360
2012-12-20 08:40:05|230
2012-12-20 08:50:06|250
2012-12-20 09:00:05|310
2012-12-20 09:10:05|180
2012-12-20 09:20:06|270
2012-12-20 09:30:05|300
2012-12-20 09:40:06|290
2012-12-20 09:50:05|580
2012-12-20 10:00:05|260
2012-12-20 10:10:06|210
2012-12-20 10:20:06|350
2012-12-20 10:30:05|410
...

我需要根据费率表中的时间戳获取正确的费率,并将价格列添加到我的结果中

查询设置结果:

ts                 | qty | rate | price
---------------------------------
...
2012-12-20 07:50:06|130|58.863|7652.19 (qty * rate)
2012-12-20 08:00:05|130|58.863 ....
2012-12-20 08:10:05|120|58.863
2012-12-20 08:20:04|130|58.863
2012-12-20 08:30:05|360|58.863
2012-12-20 08:40:05|230|58.863
2012-12-20 08:50:06|250|58.863
2012-12-20 09:00:05|310|58.863
2012-12-20 09:10:05|180|58.863
2012-12-20 09:20:06|270|58.863
2012-12-20 09:30:05|300|58.863
2012-12-20 09:40:06|290|58.863
2012-12-20 09:50:05|580|58.863
2012-12-20 10:00:05|260|58.863
2012-12-20 10:10:06|210|58.863
2012-12-20 10:20:06|350|58.863
2012-12-20 10:30:05|410|58.863
...

我的猜测是使用最近SQLite版本中出现的LEAD函数,但我不知道要在联接中使用它。

SELECT * FROM production t1 
LEFT JOIN rates t2 ON t1.ts BETWEEN t2.ts AND LEAD(t2.ts,1,0) OVER (ORDER by t2.ts)

希望您能提供帮助!

kotoko520 回答:SQLITE3:基于时间戳的联接

使用LEAD():

select p.*,round(p.qty * r.rate,2) price 
from production p inner join ( 
  select ts,rate,lead(ts) over (order by ts) nextts
  from rates  
) r on p.ts >= r.ts and (p.ts < r.nextts or r.nextts is null) 

请参见demo
结果:

| ts                  | qty | rate   | price    |
| ------------------- | --- | ------ | -------- |
| 2012-12-20 07:50:06 | 130 | 58.863 | 7652.19  |
| 2012-12-20 08:00:05 | 130 | 58.863 | 7652.19  |
| 2012-12-20 08:10:05 | 120 | 58.863 | 7063.56  |
| 2012-12-20 08:20:04 | 130 | 58.863 | 7652.19  |
| 2012-12-20 08:30:05 | 360 | 58.863 | 21190.68 |
| 2012-12-20 08:40:05 | 230 | 58.863 | 13538.49 |
| 2012-12-20 08:50:06 | 250 | 58.863 | 14715.75 |
| 2012-12-20 09:00:05 | 310 | 58.863 | 18247.53 |
| 2012-12-20 09:10:05 | 180 | 58.863 | 10595.34 |
| 2012-12-20 09:20:06 | 270 | 58.863 | 15893.01 |
| 2012-12-20 09:30:05 | 300 | 58.863 | 17658.9  |
| 2012-12-20 09:40:06 | 290 | 58.863 | 17070.27 |
| 2012-12-20 09:50:05 | 580 | 58.863 | 34140.54 |
| 2012-12-20 10:00:05 | 260 | 58.863 | 15304.38 |
| 2012-12-20 10:10:06 | 210 | 58.863 | 12361.23 |
| 2012-12-20 10:20:06 | 350 | 58.863 | 20602.05 |
| 2012-12-20 10:30:05 | 410 | 58.863 | 24133.83 |
本文链接:https://www.f2er.com/3146174.html

大家都在问