SQL查询:将时间分组为时间片然后按loginname分组,然后按时间片计算不同的登录名

时间:2013-06-14 12:02:39

标签: sql postgresql

我有一个巨大的表,包含操作的开始时间(starttime)+启动它的用户(loginname)+很多日期,这对我需要的查询来说是不重要的。

由此我想将时间分组为10分钟,然后计算10分钟时间段内不同登录名的数量。

到目前为止我有这个:

SELECT
to_timestamp( extract ( 'epoch' from starttime)::int / (600) * 600 ) AS timeslice,
loginname
from request
where starttime >= '2013-06-11 00:00:00' and starttime < '2013-06-11 01:00:00'
group by timeslice, loginname
order by timeslice asc

这给了我10分钟的时间片,每个唯一用户有一行,如何获得每个时间片一行的唯一用户数?

我有一些想法,但它们并不漂亮/快速......我想学习如果可能的话更好/更快的查询; - )

Datebase是RHEL 5.4上的PostgreSQL 8.1.18

1 个答案:

答案 0 :(得分:2)

select
    to_timestamp(extract('epoch' from starttime)::int / 600 * 600) AS timeslice,
    count(distinct loginname) total
from request
where starttime >= '2013-06-11 00:00:00' and starttime < '2013-06-11 01:00:00'
group by timeslice
order by timeslice asc