我有一张台球联赛结果表,其中包含 TIME 类型的 match_begin_time 和 match_end_time 字段。
我想知道有多少条记录属于不同的持续时间间隔,即 < 1 小时、1 小时到 1.5 小时等。
我尝试了以下代码来获取第一个和第二个时间间隔,但无论开始和结束之间的时间间隔如何,每个时间间隔都返回了所有记录:
{
SELECT
COUNT(TIMEDIFF(match_end_time, match_begin_time) BETWEEN time("00:00:00") AND time("00:59:59")) AS "< 1 Hour",
COUNT(TIMEDIFF(match_end_time, match_begin_time) BETWEEN time("01:00:00") AND time("01:30:00")) AS "1 - 1.5 Hours"
FROM lwljhb_lwl_matches
WHERE
match_end_time > 0 AND
match_end_time > 0 AND
match_end_time > Match_begin_time
使用 WHERE 子句,我可以为每个时间间隔运行一次查询,并得到正确的答案。例如,以下代码正确返回持续时间 < 1 小时的 4 条记录。
{
SELECT
TIMEDIFF(match_end_time, match_begin_time) AS "< 1 Hour"
FROM lwljhb_lwl_matches
WHERE
match_end_time > 0 AND
match_end_time > 0 AND
match_end_time > Match_begin_time AND
TIMEDIFF(match_end_time, match_begin_time) BETWEEN time("00:00:00") AND time("00:59:59")
我的 COUNT 表达式哪里出错了?
最佳答案
我会给你一个简单的查询来显示属于时间间隔“< 1 小时”和“1 小时到 1.5 小时”的记录数。我认为这对您有所帮助。
SELECT x.a AS '<1 Hour', y.b AS '1- 1.5 Hours'
FROM (SELECT COUNT(TIMEDIFF (match_end_time, match_begin_time)) AS a
FROM lwljhb_lwl_matches
WHERE TIMEDIFF (match_end_time, match_begin_time)<'01:00:00') as x,
(SELECT COUNT(TIMEDIFF (match_end_time, match_begin_time)) AS b
FROM lwljhb_lwl_matches
WHERE TIMEDIFF(match_end_time, match_begin_time) BETWEEN'01:00:00' AND '01:30:00') AS y
您可以使用 COUNT(*)
而不是 COUNT(TIMEDIFF (match_end_time, match_begin_time))
将产生相同的结果。
同样,您可以找到其他时间间隔的记录。你可以在SQLFiddle中查看我的代码.
关于mysql - 计算一段时间内的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204097/