Mysql 查询计算具有特定天数差异的行
Mysql Query for counting rows with specific days difference
要制作折线图。我想查询相差 5 天的计数。
假设如果我有以下行:
booking_date
2015-02-1
2015-02-3
2015-02-5
2015-02-6
2015-02-6
2015-02-9
2015-02-10
2015-02-15
2015-02-17
2015-02-23
2015-02-28
在上面的 table 列中,它包含日期。现在我该如何做 mysql 查询,以便它可以 return 相差 5 天,例如:
1 => 3 // count of date between 2015-02-1 & 2015-02-05 is 3
2 => 4 // count of date between 2015-02-06 & 2015-02-10 is 4
3 => 1 // count of date between 2015-02-11 & 2015-02-15 is 1
4 => 1 // count of date between 2015-02-16 & 2015-02-20 is 1
5 => 1 // count of date between 2015-02-21 & 2015-02-25 is 1
6 => 1 // count of date between 2015-02-26 & 2015-02-30 is 1
有没有像上面这样的直接查询方式。我不太擅长mysql。但可以做得很好php。
你的意思是做这样的事情:
SELECT COUNT(1) FROM {table_name} WHERE booking_date > 2015-02-01 AND booking_date < 2015-02-05
?
(完全脱离记忆,因此您可能需要稍微改变它)
SELECT count(*)
FROM tbl
WHERE booking_date >= start_date
AND booking_date <= end_date
您可以执行以下操作以在同一个查询中获取所有内容。
首先获取5天后开始分组的日期的unix时间戳。在您的示例中是 2015-02-01 -> 1422748800
那么查询如下:
SELECT COUNT(*), FLOOR((UNIX_TIMESTAMP(booking_date) - 1422748800)/ (60*60*24*5)) as FiveDayPackNumber from tbl GROUP BY FLOOR((UNIX_TIMESTAMP(booking_date) - 1422748800)/ (60*60*24*5))
尚未对其进行测试,因此可能需要进行一些调整,但您可以理解:它将根据自初始日期以来经过的 5 天包装的数量对它们进行分组,从 0 开始。
要制作折线图。我想查询相差 5 天的计数。 假设如果我有以下行:
booking_date
2015-02-1
2015-02-3
2015-02-5
2015-02-6
2015-02-6
2015-02-9
2015-02-10
2015-02-15
2015-02-17
2015-02-23
2015-02-28
在上面的 table 列中,它包含日期。现在我该如何做 mysql 查询,以便它可以 return 相差 5 天,例如:
1 => 3 // count of date between 2015-02-1 & 2015-02-05 is 3
2 => 4 // count of date between 2015-02-06 & 2015-02-10 is 4
3 => 1 // count of date between 2015-02-11 & 2015-02-15 is 1
4 => 1 // count of date between 2015-02-16 & 2015-02-20 is 1
5 => 1 // count of date between 2015-02-21 & 2015-02-25 is 1
6 => 1 // count of date between 2015-02-26 & 2015-02-30 is 1
有没有像上面这样的直接查询方式。我不太擅长mysql。但可以做得很好php。
你的意思是做这样的事情:
SELECT COUNT(1) FROM {table_name} WHERE booking_date > 2015-02-01 AND booking_date < 2015-02-05
?
(完全脱离记忆,因此您可能需要稍微改变它)
SELECT count(*)
FROM tbl
WHERE booking_date >= start_date
AND booking_date <= end_date
您可以执行以下操作以在同一个查询中获取所有内容。
首先获取5天后开始分组的日期的unix时间戳。在您的示例中是 2015-02-01 -> 1422748800
那么查询如下:
SELECT COUNT(*), FLOOR((UNIX_TIMESTAMP(booking_date) - 1422748800)/ (60*60*24*5)) as FiveDayPackNumber from tbl GROUP BY FLOOR((UNIX_TIMESTAMP(booking_date) - 1422748800)/ (60*60*24*5))
尚未对其进行测试,因此可能需要进行一些调整,但您可以理解:它将根据自初始日期以来经过的 5 天包装的数量对它们进行分组,从 0 开始。