sqlite 怎样才能找到最近的时间?

rseugnpd  于 2022-11-15  发布在  SQLite
关注(0)|答案(1)|浏览(234)
  • A有字段RefuelIdRefuelTime。记录我给车加油的时间。
  • B具有字段PriceUpdateTime。记录汽油价格和汽油价格更新时间。
  • 想要结果:A.RefuelIdA.RefuelTimeB.PriceB.UpdateTime

B.UpdateRefuelTime之前的关闭时间。我尝试了left join,但表AB之间没有公共字段。退货笛卡尔乘积。
ARefuelRecord
RefuelId|RefuelTime

1|2022-02-01 12:15:00
2|2022-03-01 12:15:00
3|2022-04-01 12:15:00
BGasUpdateRecord
UpdateTime,|价格

2022-01-20 0:00:00|9.0
2022-02-20 0:00:00|8.1
2022-03-20 0:00:00|7.2
结果表:
|||
-|-|
1|2022-02-01 12:15:00|2022-01-20 0:00:00
2|2022-03-01 12:15:00|2022-02-20 0:00:00
3|2022-04-01 12:15:00|2022-03-20 0:00:00
SQL:

Create table RefuelRecord (RefuelId int, RefuelTime datetime);
INSERT INTO RefuelRecord VALUES(1, '2022-02-01 12:15:00');
INSERT INTO RefuelRecord VALUES(2, '2022-03-01 12:15:00');
INSERT INTO RefuelRecord VALUES(3, '2022-04-01 12:15:00');

Create table PriceUpdateRecord (UpdateTime datetime, Price double);
INSERT INTO PriceUpdateRecord VALUES('2022-01-20 12:15:00', 9.0);
INSERT INTO PriceUpdateRecord VALUES('2022-02-20 12:15:00', 8.0);
INSERT INTO PriceUpdateRecord VALUES('2022-03-20 12:15:00', 7.0);
ntjbwcob

ntjbwcob1#

UpdateTime应小于RefuelTime的条件下,执行RefuelRecordPriceUpdateRecordLEFT联接。
然后使用聚合和SQLite的裸列功能,为每个RefuelId获取PriceUpdateRecord中具有最大UpdateTime的行:

SELECT r.RefuelId, 
       r.RefuelTime,
       MAX(p.UpdateTime) UpdateTime,
       p.Price
FROM RefuelRecord r LEFT JOIN PriceUpdateRecord p
ON p.UpdateTime < r.RefuelTime
GROUP BY RefuelId;

请参阅demo

相关问题