【问题标题】:SQLite: Sum of differences between two dates group by every dateSQLite:按每个日期分组的两个日期之间的差异总和
【发布时间】:2018-09-03 09:49:23
【问题描述】:

我有一个带有开始和停止日期时间的 SQLite 数据库

通过以下 SQL 查询,我得到了开始和停止之间的不同小时数:

SELECT starttime, stoptime, cast((strftime('%s',stoptime)-strftime('%s',starttime)) AS real)/60/60 AS diffHours FROM tracktime; 

我需要一个 SQL 查询,它提供多个时间戳的总和,按每天分组(也包括时间戳之间的整个日期)。

结果应该是这样的:

  • 2018-08-01:12 小时
  • 2018-08-02: 24 小时
  • 2018-08-03: 12 小时
  • 2018-08-04:0 小时
  • 2018-08-05:1 小时
  • 2018-08-06: 14 小时
  • 2018-08-07:8 小时

【问题讨论】:

  • 你的sqlite版本支持CTE吗?
  • 是的,支持 CTE
  • 我写了一个答案你可以试试。

标签: sql sqlite datetime group-by timestamp


【解决方案1】:

你可以试试这个,用CTE RECURSIVE为每个日期的开始时间和结束时间做一个日历表,然后做一些计算。

架构 (SQLite v3.18)

CREATE TABLE tracktime(
  id int,
  starttime timestamp,
  stoptime timestamp
);

insert into  tracktime values 
(11,'2018-08-01 12:00:00','2018-08-03 12:00:00');
insert into  tracktime values 
(12,'2018-09-05 18:00:00','2018-09-05 19:00:00');

查询 #1

WITH RECURSIVE cte AS (
    select id,starttime,date(starttime,'+1 day') totime,stoptime
    from tracktime
    UNION ALL
    SELECT  id,
            date(starttime,'+1 day'),
            date(totime,'+1 day'),
            stoptime
    FROM cte
    WHERE date(starttime,'+1 day') < stoptime
)

SELECT  strftime('%Y-%m-%d', starttime),(strftime('%s',CASE 
              WHEN totime > stoptime THEN stoptime
              ELSE totime
            END) -strftime('%s',starttime))/3600 diffHour
FROM cte;

| strftime('%Y-%m-%d', starttime) | diffHour |
| ------------------------------- | -------- |
| 2018-08-01                      | 12       |
| 2018-09-05                      | 1        |
| 2018-08-02                      | 24       |
| 2018-08-03                      | 12       |

View on DB Fiddle

【讨论】:

  • 谢谢你,我喜欢你的解决方案!如何重写应用程序,小时数以小数点后两位显示?
  • @baconLX 如果要显示两位小数可以尝试使用printf函数db-fiddle.com/f/wBqvZniHT4FzuSubu7w3zf/2
  • 例如,如果我将停止时间增加半小时,总时间仍然会显示 x.00,尽管它实际上应该是 x.50。
猜你喜欢
  • 2014-10-12
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2022-01-06
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多