如何计算组数据的日期差

wqsoz72f  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(293)

我想在分组数据时计算日期时间差。
让我们看看表内容示例:

id | session_id | created
1  | 101        | 1/10/2010 9:30:10
2  | 102        | 1/10/2010 9:31:10
3  | 101        | 1/10/2010 9:32:10
4  | 103        | 1/10/2010 9:35:10
5  | 102        | 1/10/2010 9:38:10
6  | 103        | 1/10/2010 9:39:10

输出应如下:

session_id | time_count
101        | 2 (minutes)
102        | 7 (minutes)
103        | 4 (minutes)

所以这里我想计算“created”字段的时间差,数据是按会话id分组的。
任何帮助都会很好。提前感谢:)
我的情况:
我有一个包含以下字段的表:

id, session_id, platform, event, created

有两个事件( Start,End )
现在,如果有相同会话id的开始和结束记录,则我需要完成此会话所需的时间。
但如果我有两个开始会话,但只有一个结束会话,那么我不想要第二个会话的时间差,因为它没有结束

ef1yzkbh

ef1yzkbh1#

试试这个:
表架构:

CREATE TABLE A(id INT, session_id INT,Event VARCHAR(20), created DATETIME);

INSERT INTO A VALUES(1, 101,'Start','2010/10/01 9:30:10')
,(2, 102,'Start'  , '2010/10/01 9:31:10')
,(3, 101,'End'    , '2010/10/01 9:32:10')
,(4, 103,'Start'  , '2010/10/01 9:35:10')
,(5, 102,'End'    , '2010/10/01 9:38:10')
,(6, 103,'End'    , '2010/10/01 9:39:10')
,(7, 101,'Start'  , '2010/10/01 9:39:10')
,(8, 102,'Start'  , '2010/10/01 9:39:10')
,(9, 101,'End'    , '2010/10/01 9:55:10');

查询:

SELECT D.session_id
    ,TIMESTAMPDIFF(MINUTE,MIN(D.created), MAX(D.created)) time_count
FROM(
  SELECT a.id,a.session_id,a.created
    ,ROUND(count(*)/2,0) as RN 
    ,count(*) as row_number1 
  FROM a AS a
  JOIN a AS b ON a.session_id = b.session_id AND a.id >= b.id
  GROUP BY a.id,a.session_id,a.created
  ORDER BY 2,3
    )D
GROUP BY D.session_id,D.RN
HAVING COUNT(1)>1

输出:

session_id  time_count
101         2
102         7
103         4
101         16

小提琴:
检查#sql fiddle中的输出

iq0todco

iq0todco2#

你可以试试它的辛塔克斯:

WITH cte AS (
    SELECT
        session_id,
        DATEDIFF(minute, created, LAG(created, 1)) AS diff,
        ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY created) rn
    FROM yourTable
)

SELECT

        session_id,
        diff AS time_count
    FROM cte
    WHERE rn % 2 = 0

;
kknvjkwl

kknvjkwl3#

SELECT session_id,
DATEDIFF(MINUTE, MAX(created), MIN(created)) AS diff
FROM table
GROUP BY session_id

相关问题