我有一个包含一些库存数据的SQLite数据库。第一列是日期时间,最后一列是股票的代码/名称。其他列是价格和数量,但此处不相关。
这是头和尾:
sqlite> select * from History order by dt ASC limit 5;
"2003-01-02 11:00:00",9.65,9.65,9.65,9.65,1000.0,ACY
"2003-01-02 11:00:00",62.0,62.0,62.0,62.0,30000.0,AMER
"2003-01-02 11:00:00",0.345,0.345,0.34,0.34,60000.0,CNR
"2003-01-02 11:00:00",1.41,1.41,1.41,1.41,45000.0,CRU
"2003-01-02 11:00:00",32.8,32.85,32.8,32.85,38000.0,DNBNOR
sqlite> select * from History order by dt DESC limit 5;
"2010-04-09 19:15:00",3.045,3.05,3.045,3.05,6000.0,ACTA
"2010-04-09 19:15:00",117.4,117.4,117.1,117.1,14900.0,ACY
"2010-04-09 19:15:00",3.15,3.15,3.15,3.15,7800.0,AGI
"2010-04-09 19:15:00",160.25,160.25,160.25,160.25,11300.0,AKER
"2010-04-09 19:15:00",94.925,94.925,94.65,94.775,32900.0,AKSO
如您所见,我拥有2003年至2010年的数据,大约有130只股票。但由于合并,交换等原因,并非所有股票都在同一时间范围内。
我要找出的是大多数股票共有的(最长)时间跨度,可以说130支股票中有50支是在2004-2010年之间,并返回日期范围和股票名称。使用SQLite是否可以?
编辑:有关我认为基本输出看起来如何的示例
starttime endtime totaltime stock
"2003-01-02 11:00:00", "2010-04-09 19:15:00", 12345678, ACY
"2003-01-02 11:00:00", "2007-01-07 16:00:00", 12345, CNR
...
然后我可以按totaltime
进行排序,以查看哪些股票的数据最多。
答案 0 :(得分:1)
请回答我的问题。我不是SQLite的专家,但没有其他人响应,因此“应该”下的查询有效。尝试并根据需要进行改进:
with stock_life as (
select
stock,
min(recorded_at) as starttime,
max(recorded_at) as endtime,
julianday(max(recorded_at)) - julianday(max(recorded_at)) as totaltime
group by stock
)
select * from stock_life
order by totaltime desc
limit 50