我有一张随机生成的表格。它有3列:P_Id,日期(插入行的位置)和文本。让我们说文本可以是各种动物。所以表格看起来像
1 2011-06-15 03:04:05 cow
2 2011-06-15 03:04:15 dog
3 2011-06-15 03:04:19 bird
4 2011-06-15 03:04:30 cow
5 2011-06-15 03:04:30 dog
6 2011-06-15 03:04:35 cow
....
挑选所有在最近进入的最后30分钟内至少发生过两次的动物的查询是什么?例如,这里的牛在最近一次进入的最后30分钟内发生了3次,即3:04:35,并且发生了两次。不会选择Bird,因为它只发生一次。
答案 0 :(得分:2)
总是有直接的方式(即使用子查询来提取时间戳范围然后照常进行):
select name, count(name)
from your_table
where created_at >= (
select max(created_at) - INTERVAL 30 MINUTE
from your_table
)
group by name
having count(name) >= 2
答案 1 :(得分:1)
假设你检查每个事件的最后30分钟
select name, count(name)
from your_table t1
join (
select name, max(created_at) created_at
from your_table t2
) on t1.name = t2.name
where datediff (minute,t1.created_at,t2.created_at)<=30
group by name
having count(name) >= 2
答案 2 :(得分:0)
select animal, count(*)
from MyTable
where date >= (currentDate - 30 minutes)
group by animal
having count(*) >= 2
答案 3 :(得分:0)
形成一个名为latest_animals的内部表,它将计算每只动物的最新进入日期。 形成另一个名为previous_animals的内部表,它将计算每只动物的上一个最新进入日期。
根据动物名称在这两个表之间进行左联接,并根据两个日期之间的时差来过滤记录。
SELECT latest_animals.animal_name, TIME_DIFF(latest_animals.created_at, previous_animals.created_at) created_diff FROM
(
SELECT animal_name, MAX(date) created_at FROM animals GROUP BY animal_name
) latest_animals
LEFT JOIN
(
SELECT animal_name, MAX(date) created_at FROM animals GROUP BY animal_name WHERE id NOT IN
(SELECT id, MAX(date) FROM animals GROUP BY animal_name)
) previous_animals
ON latest_animals.animal_name = previous_animals.animal_name
WHERE created_diff > INTERVAL 30 MINUTE