根据记录之间的数据关系进行分组

时间:2014-01-23 09:43:56

标签: sql sqlite group-by grouping having

这是我的表:

ID | startTime  | endTime 
0  | 1380209017 | 1380470025
1  | 1390480010 | 1390480018
2  | 1390480218 | 1390480888 
3  | 1390480999 | 1390490888 

现在我按照以下方式获取每天的记录数

SELECT 
count(date(tripStartTime,'unixepoch')) AS count,
date(tripStartTime,'unixepoch') AS date 
FROM TripsCalculated  
GROUP BY date(tripStartTime,'unixepoch')

结果是这样的:

count | date 
1  | 2013-09-29
3  | 2014-01-23

现在我需要获得每天的记录数量,但是<5分钟的记录应该算作一个记录

count | date 
1  | 2013-09-29
1  | 2014-01-23

我可以使用SQLite实现这一目标吗?怎么样?顺便说一句,我的平台是安卓的。

1 个答案:

答案 0 :(得分:0)

如果您不关心差距,可以使用自联接轻松访问上一行。

SELECT 
   COUNT(*) AS COUNT,
   tripStartTime AS DATE 
FROM 
 (
   SELECT DATE(tripStartTime,'unixepoch') AS tripStartTime
   FROM TripsCalculated AS t1 LEFT JOIN TripsCalculated AS t2
   ON t2.id = t1.id+1
   WHERE t2.tripStartTime - t1.tripEndTime > 5*60 
 )
GROUP BY DATE(tripStartTime,'unixepoch')

检查WHERE条件的逻辑,它未经测试,我不喜欢自连接,因为每列都存在两次: - )