3

我有一个 MySQL 查询,我正在运行该查询以计算在 15 分钟时间间隔内的任何给定时间(在任何给定日期等)内为用户预订了多少电话。到目前为止,我有:

    SELECT
date_action,
DATE_FORMAT(date_action, "%i") AS minute,
CASE 
    WHEN minute(date_action) BETWEEN 0 and 14 THEN '00'
    WHEN minute(date_action) BETWEEN 15 and 29 THEN '15'
    WHEN minute(date_action) BETWEEN 30 and 44 THEN '30'
    WHEN minute(date_action) BETWEEN 45 and 59 THEN '45'
END AS intervals
FROM
clients
WHERE
HOUR(date_action) = 09
AND DAY(date_action) = 15
AND MONTH(date_action) = 07
AND YEAR(date_action) = 2013

这很好用,但我缺少的神奇成分是分配给每个间隔的调用次数的“计数”,因此例如上面的代码产生:

Date_time - Minute - Interval
2013-07-15 09:54:24 - 54 - 45
2013-07-15 09:29:32 - 29 - 15
2013-07-15 09:13:33 - 13 - 00
2013-07-15 09:53:53 - 53 - 45
2013-07-15 09:00:49 - 00 - 00

因此,我将我的分钟数转换为间隔,因为我只想为每个间隔返回 1 行,然后在其上附加一列,其中包含该间隔内的呼叫次数,即

Interval - Count
45 - 2
15 - 1
00 - 2

我觉得我的头撞在这块砖墙上已经太久了,所以任何帮助都将不胜感激。虽然在查询之后会进行一些后处理,但如果可能的话,我更愿意在 SQL 中完成这一切。:)

4

2 回答 2

3

您可以按间隔分组并选择计数。

SELECT
    count(date_action) as count,
    CASE 
        WHEN minute(date_action) BETWEEN 0 and 14 THEN '00'
        WHEN minute(date_action) BETWEEN 15 and 29 THEN '15'
        WHEN minute(date_action) BETWEEN 30 and 44 THEN '30'
        WHEN minute(date_action) BETWEEN 45 and 59 THEN '45'
    END AS intervals
FROM
    clients
WHERE
    HOUR(date_action) = 09
    AND DAY(date_action) = 15
    AND MONTH(date_action) = 07
    AND YEAR(date_action) = 2013
    AND rep_id = 28
GROUP BY intervals
于 2013-07-04T09:35:14.900 回答
0
select period, Sum(NumberOfTimes) as NumberOfTimes
From
(Select minute(date_action) % 15 as period, 1 as NumberOfTimes
From Clients
WHERE
    HOUR(date_action) = 09
    AND DAY(date_action) = 15
    AND MONTH(date_action) = 07
    AND YEAR(date_action) = 2013
    AND rep_id = 28
) dummyName
Group By period

将是另一种方式

% 是模运算符

于 2013-07-04T09:43:15.010 回答