在SQL中,如何将时间戳拆分为多个区间,但以当天的第一条记录作为第一个区间的开始?
In SQL, how to split timestamps into several intervals but with the first record of the day as the beginning of the first interval?
PostgreSQL 9.5
我的数据集如下所示:
我想将同一天的记录拆分为1分钟的间隔,但每个间隔的开始作为间隔的最小值。
有了这个数据集,我的理想输出应该是这样的:
比如2014-05-27,最小值是15:09:40,所以第一个一分钟的间隔就是15:09:40 - 15:10:40
,一共有3条记录。对于下一个间隔,15:11:01 - 15:12:01
,有一个记录。
希望我已经说清楚了。提前致谢。
您可以尝试使用 CTE 或子查询来获得一个 gap_seconds,它表示减去 occurred_at
和前一个 occurred_at
行的值,然后制作一个 grp 列来计算保持差距的价值观。
;WITH CTE AS (
SELECT *,
FLOOR(SUM(gap_seconds) OVER(ORDER BY occurred_at) / 60) grp
FROM (
SELECT *,
EXTRACT(SECOND FROM occurred_at - LAG(occurred_at,1,occurred_at) OVER(ORDER BY occurred_at)) gap_seconds
FROM T
) t1
)
SELECT MIN(occurred_at) occurred_at,
COUNT(*)
FROM CTE
GROUP BY grp
ORDER BY 1
另一个例子,我们可以像下面这样查询
除以120秒
WITH CTE AS (
SELECT *,
FLOOR(SUM(gap_seconds) OVER(ORDER BY occurred_at) / 120) grp
FROM (
SELECT *,
EXTRACT(SECOND FROM occurred_at - LAG(occurred_at,1,occurred_at) OVER(ORDER BY occurred_at)) gap_seconds
FROM T
) t1
)
SELECT MIN(occurred_at) occurred_at,
COUNT(*)
FROM CTE
GROUP BY grp
ORDER BY 1
PostgreSQL 9.5
我的数据集如下所示:
我想将同一天的记录拆分为1分钟的间隔,但每个间隔的开始作为间隔的最小值。
有了这个数据集,我的理想输出应该是这样的:
比如2014-05-27,最小值是15:09:40,所以第一个一分钟的间隔就是15:09:40 - 15:10:40
,一共有3条记录。对于下一个间隔,15:11:01 - 15:12:01
,有一个记录。
希望我已经说清楚了。提前致谢。
您可以尝试使用 CTE 或子查询来获得一个 gap_seconds,它表示减去 occurred_at
和前一个 occurred_at
行的值,然后制作一个 grp 列来计算保持差距的价值观。
;WITH CTE AS (
SELECT *,
FLOOR(SUM(gap_seconds) OVER(ORDER BY occurred_at) / 60) grp
FROM (
SELECT *,
EXTRACT(SECOND FROM occurred_at - LAG(occurred_at,1,occurred_at) OVER(ORDER BY occurred_at)) gap_seconds
FROM T
) t1
)
SELECT MIN(occurred_at) occurred_at,
COUNT(*)
FROM CTE
GROUP BY grp
ORDER BY 1
另一个例子,我们可以像下面这样查询
除以120秒WITH CTE AS (
SELECT *,
FLOOR(SUM(gap_seconds) OVER(ORDER BY occurred_at) / 120) grp
FROM (
SELECT *,
EXTRACT(SECOND FROM occurred_at - LAG(occurred_at,1,occurred_at) OVER(ORDER BY occurred_at)) gap_seconds
FROM T
) t1
)
SELECT MIN(occurred_at) occurred_at,
COUNT(*)
FROM CTE
GROUP BY grp
ORDER BY 1