我需要一个SQL查询来检查一个人在一年中是否连续两周处于活动状态。
例如,
Table1:
Name | Activity | Date
Name1|Basketball| 08-08-2014
Name2|Volleyball| 08-09-2014
Name3|None | 08-10-2014
Name1|Tennis | 08-14-2014我想检索Name1,因为这个人在一年中连续两周都很活跃。
到目前为止,这是我的疑问:
SELECT DISTINCT Name
FROM Table1
Where YEAR(Date) = 2014 AND
Activity NOT 'None' AND这就是我需要在连续两周内检查活动的逻辑。一周可以说是7到14天后。我和MYSQL一起工作。
发布于 2014-08-06 12:48:56
可以使用exists子查询执行逻辑:
select t.*
from table1 t
where exists (select 1
from table1 t2
where t2.name = t.name and
t2.date between t.date + 7 and t.date + 14
);发布于 2014-08-06 12:58:54
我避免了故意在where子句中使用Date,并建议您也这样做。在多行数据上使用函数来适应单一标准(2014年)对我来说是没有意义的,而且它还会破坏索引的有效性(参见wikipedia中的"sargable“)。通过日期范围IMHO定义过滤器要容易得多。
我使用了一个相关的子查询来派生nxt_date,这可能不是很好的扩展,但是总的来说,性能将很可能取决于您的索引。
select distinct
name
from (
select
t.name
, t.Activity
, t.`Date`
, (
select min(table1.`Date`) from table1
where t.name = table1.name
and table1.Activity <> 'None'
and table1.`Date` > t.`Date`
) as nxt_date
from table1 as t
where ( t.`Date` >= '2014-01-01' and t.`Date` < '2015-01-01' )
and t.Activity <> 'None'
) as sq
where datediff(sq.nxt_date, sq.`Date`) <= 14
;发布于 2014-08-06 13:22:03
我不知道这是否与性能有关,但我喜欢简洁的查询:
SELECT t1.Name
FROM Table1 t1, Table1 t2
Where t1.Name=t2.Name AND
t1.Date >= '2014-01-01' AND t1.Date < '2015-01-01' AND
t1.Activity <> 'None' AND
t1.Date < t2.Date AND
datediff(t2.Date, t1.Date) <= 14我喜欢@user2067753关于YEAR(date)的提示。
我使用上面的答案的sqlfiddle来检查使用explain 语法的性能。避免像VACN的回答或is这样的子查询似乎是有益的(参见加入 vs 子查询)
https://stackoverflow.com/questions/25160423
复制相似问题