我有一个表格,其中列出了在 sqlite3 数据库中玩过的游戏。 “日期时间”字段是游戏结束时的日期时间。 “持续时间”字段是游戏持续的秒数。我想知道过去 24 小时中至少同时运行 5 场比赛的百分比。我想知道在给定时间运行了多少游戏:
select count(*)
from games
where strftime('%s',datetime)+0 >= 1257173442 and
strftime('%s',datetime)-duration <= 1257173442
如果我有一个表,它只是一个每秒(或每 30 秒或其他时间)的列表,我可以像这样做一个有意的笛卡尔积:
select count(*)
from (
select count(*) as concurrent, d.second
from games g, date d
where strftime('%s',datetime)+0 >= d.second and
strftime('%s',datetime)-duration <= d.second and
d.second >= strftime('%s','now') - 24*60*60 and
d.second <= strftime('%s','now')
group by d.second) x
where concurrent >=5
有没有办法即时创建这个日期表?或者我可以获得与此类似的效果,而不必实际创建一个新表,该表只是本周所有秒数的列表?
谢谢
最佳答案
首先,我想不出一种通过即时创建表格或不借助额外表格来解决您的问题的方法。对不起。
我的建议是您依赖静态 Numbers 表。
创建一个具有以下格式的固定表:
CREATE TABLE Numbers (
number INTEGER PRIMARY KEY
);
用 24 小时中的秒数填充它 (24*60*60 = 84600)。我会使用任何脚本语言通过插入语句来做到这一点:
insert into numbers default values;
现在 Numbers 表中有数字 1 到 84600。您的查询将被修改为:
select count(*)
from (
select count(*) as concurrent, strftime('%s','now') - 84601 + n.number second
from games g, numbers n
where strftime('%s',datetime)+0 >= strftime('%s','now') - 84601 + n.number and
strftime('%s',datetime)-duration <= strftime('%s','now') - 84601 + n.number
group by second) x
where concurrent >=5
我认为,在没有过程语言的情况下,这是你能做到的最好的结果。
关于sqlite3 : Need to Cartesian On date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663414/