在< 15分钟和15到30分钟的sql查询内计算用户数

时间:2017-12-11 09:47:41

标签: sql sql-server

表名客户访问

CustomerId, phoneMacAddress,  CreateDatetime 
1002        1b:66:41:11:26:16  2017-07-17 07:33:31.300
1003        cb:45:85:25:2:0    2017-07-17 07:05:21.200
1004        3o:09:ab:1c:5:ab   2017-07-17 10:03:01.400
1002        1b:66:41:11:26:16  2017-07-17 08:12:03.543
1002        1b:66:41:11:26:16  2017-07-17 08:12:03.543
1002        1b:66:41:11:26:16  2017-07-17 08:09:27.527

如何获取此格式的数据:

<15min      15-30min      >30min
1           4             0 

2 个答案:

答案 0 :(得分:0)

SQL SERVER的更新

#Last 15 mins
SELECT COUNT(CustomerId) FROM customer_visit WHERE CreateDatetime >= DateADD(mi, -15, CURRENT_TIMESTAMP) and CreateDatetime <= CURRENT_TIMESTAMP;

#Between 15 to 30 min
SELECT COUNT(CustomerId) FROM customer_visit WHERE CreateDatetime >= DateADD(mi, -30, CURRENT_TIMESTAMP) and CreateDatetime <= DateADD(mi, -15, CURRENT_TIMESTAMP);

在MySQL中,您可以使用此查询并调整时间间隔。

#Last 15 mins
SELECT COUNT(CustomerId) FROM customer_visit WHERE CreateDatetime >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 15 minute) and CreateDatetime <= UTC_TIMESTAMP();

#Between 15 to 30 min
SELECT COUNT(CustomerId) FROM customer_visit WHERE CreateDatetime >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 minute) and CreateDatetime <= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 15 minute);

我使用UTC_TIMESTAMP()但您可以使用NOW(),具体取决于您在数据库中存储日期时间的方式。

答案 1 :(得分:0)

您可以使用lead()和一些日期/时间算法。像这样:

select sum(case when next_cdt < dateadd(minute, 15, CreateDateTime) then 1
                else 0 end) as [<15min],
       sum(case when next_cdt >= dateadd(minute, 15, CreateDateTime) and
                     next_cdt < dateadd(minute, 30, CreateDateTime)
                then 1
                else 0 end) as [15-30min],
       sum(case when next_cdt >= dateadd(minute, 30, CreateDateTime) then 1
                else 0 end) as [<30min]  
from (select t.*,
             lead(CreateDatetime) over (order by CreateDatetime) as next_cdt
      from t
     ) t;