Android 日期差之和
我正在开发一个android应用程序,它有一个名为“entries”的表 表结构如下所示Android 日期差之和,android,sql,sql-server,database,sqlite,Android,Sql,Sql Server,Database,Sqlite,我正在开发一个android应用程序,它有一个名为“entries”的表 表结构如下所示 id name operation date ---------------------------------------------- 1 engine on 08-03-2015 19.22 2 engine off 08-03-2015 19.23 3 light on
id name operation date
----------------------------------------------
1 engine on 08-03-2015 19.22
2 engine off 08-03-2015 19.23
3 light on 08-03-2015 19.23
4 light off 08-03-2015 19.28
5 engine on 08-03-2015 19.28
6 engine off 08-03-2015 19.30
name duration
----------------
engine 3
light 5
我想得到如下输出
id name operation date
----------------------------------------------
1 engine on 08-03-2015 19.22
2 engine off 08-03-2015 19.23
3 light on 08-03-2015 19.23
4 light off 08-03-2015 19.28
5 engine on 08-03-2015 19.28
6 engine off 08-03-2015 19.30
name duration
----------------
engine 3
light 5
这是发动机和指示灯处于接通状态时的总时间。
对于发动机,添加了时间差b/w打开和关闭状态,并将其作为输出。对于灯光,情况类似。
有人能帮我吗
我不知道如何开始。
提前感谢您可以使用ANSI SQL(与SQL Server和SQLite兼容)通过使用相关子查询获取每个on的“off”值来完成此操作:
select name,
sum(strftime('%s', offtime) - strftime('%s', date)) as numseconds
from (select e.*,
(select min(e2.date)
from entries e2
where e2.name = e.name and
e2.date > e.date and
e.operation = 'off'
) as offtime
from entries e
where operation = 'on'
) e
group by name;
注意,这使用SQLite构造来计算持续时间(以秒为单位)。SQL Server中有一个类似的构造,它使用datediff()
编辑:
在SQL Server中:
select name,
datediff(seconds, date, offtime) as numseconds
from (select e.*,
(select min(e2.date)
from entries e2
where e2.name = e.name and
e2.date > e.date and
e.operation = 'off'
) as offtime
from entries e
where operation = 'on'
) e
group by name;
您使用的是SQL Server还是SQLite?我使用的是SQLite android数据库。我收到以下错误消息:Msg 195,级别15,状态10,第2行“strftime”不是可识别的内置函数名。Msg 156,级别15,状态1,第8行关键字“off”附近的语法不正确。
strftime()
是SQLite不可分割的一部分:。不过,您的错误消息可能是SQL Server错误消息,这一点相当可疑。感谢gordon,让我在sqlite中尝试,并让您知道结果。sqlite上的错误显示为[no-this column:off]异常名称:NS\u error\u FAILURE异常消息:组件返回的故障代码:0x80004005(NS\u error\u FAILURE)[mozIStorageConnection.createStatement]