当我对数据进行分组时,我想计算日期 - 时间差异。
让我们看一下表格内容示例:
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)
所以我想在这里计算出来的'时间差。数据字段,按session_id分组。
任何帮助都会很棒。在此先感谢:)
我的情况:
我有一个包含以下字段的表格:
id, session_id, platform, event, created
有2个事件(Start,End
)
现在,如果有相同session_id的开始和结束记录,那么我想要完成此会话所需的时间。
但是,如果我有2个开始会话,但只有1个结束会话,那么我不希望第2个会话的时间差,因为它没有结束
答案 0 :(得分:0)
SELECT session_id,
DATEDIFF(MINUTE, MAX(created), MIN(created)) AS diff
FROM table
GROUP BY session_id
答案 1 :(得分:0)
试试这个:
表架构:
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
中的输出答案 2 :(得分:-1)
你可以尝试一下sintax:
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
;