【问题标题】:sql sum of date differencessql日期差异总和
【发布时间】:2015-03-08 14:11:43
【问题描述】:

我正在开发一个 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        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

这是引擎和灯在开启状态下的总时间。 详细来说,引擎会添加黑白开启和关闭状态的时间差并将其作为输出。对于灯光也是如此。 任何人请帮助我 不知道如何开始。 提前致谢

【问题讨论】:

  • 您使用的是 SQL Server 还是 SQLite?
  • 我正在使用 sqlite android 数据库

标签: android sql sql-server database sqlite


【解决方案1】:

您可以使用 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;

【讨论】:

  • 我收到以下错误消息 195,级别 15,状态 10,第 2 行“strftime”不是可识别的内置函数名称。消息 156,级别 15,状态 1,第 8 行关键字“off”附近的语法不正确。
  • strftime() 是 SQLite 不可或缺的一部分:sqlite.org/lang_datefunc.html。但是,您的错误消息是 SQL Server 错误消息,这很可疑。
  • 感谢 gordon 让我在 sqlite 中试一试,结果会告诉你
  • 它在 sqlite 上显示错误为 [ no such column: off ] 异常名称:NS_ERROR_FAILURE 异常消息:组件返回失败代码:0x80004005 (NS_ERROR_FAILURE) [mozIStorageConnection.createStatement]
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 2018-05-09
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多