我在mysql query, return rows when condition is satisfied
上发布了更新的问题感谢那些帮助过......
好的,我正在对此进行第二次尝试,因为我搞砸了原来的问题。我已经更正了日期格式以匹配mysql。此外,我实际上是根据值的百分比在查询中存档状态值,即,如果它在最高观察值的85%以内,则标记为高,如果它在低水位的15%内,则标记为低。
其格式为name,test_date,score。
类似
John, 2014-10-12, 87
John, 2014-10-13, 87
John, 2014-10-14, 33
John, 2014-10-15, 32
John, 2014-10-16, 44
John, 2014-10-17, 87
John, 2014-10-18, 89
John, 2014-10-19, 90
Jane, 2014-10-12, 32
Jane, 2014-10-13, 87
Jane, 2014-10-14, 33
Jane, 2014-10-15, 88
Jane, 2014-10-16, 44
Jane, 2014-10-17, 87
Jane, 2014-10-18, 89
Jane, 2014-10-19, 90
以下是我当前必须返回仅在高水位线或低水位线内的数据的查询。
select userdata.name, test_date, score, if(score >=.85*temp.High,"High","Low")
from userdata
inner join (select name, Min(score) as Low, Max(score) as High
from userdata where (test_date between '2013-12-02' and '2014-12-01') group by name)
as temp on userdata.name=temp.name where (score >= .85*temp.High or score <= 1.15*temp.Low)
and test_date between '2013-12-02' and '2014-12-01' order by name, test_date
假设最高为96,最低为35,则返回
等数据 John, 2012-12-02, 90, High
John, 2012-12-03, 40, Low
John, 2012-12-04, 41, Low
John, 2012-12-05, 95, High
John, 2012-12-05, 94, High
John, 2012-12-02, 90, High
Jane, 2012-12-03, 40, Low
Jane, 2012-12-04, 41, Low
Jane, 2012-12-05, 41, Low
Jane, 2012-12-06, 41, Low
Jane, 2012-12-06, 41, Low
Jane, 2012-12-11, 89, High
现在我想看看我是否可以修改我的查询以仅返回更改状态。我查看了所提供的答案,但是我将我们的元素与原始查询结合起来以产生所需的结果。感谢您已经给出的帮助,我为第一次没有正确填写我的问题而道歉。
答案 0 :(得分:1)
您可以使用变量或获取以前的状态来执行此操作。这是第二种方法:
select t.*
from (select t.*,
(select t2.state
from onetable t2
where t2.name = t.name and t2.date < t.date
order by t2.date desc
limit 1
) as prev_state
from onetable t
) t
where prev_state is null or prev_state <> state;
为了提高性能,您需要onetable(name, date, state)
上的索引。
答案 1 :(得分:1)
你可以使用MySQL变量来做到这一点。
每当日期不匹配且条件不匹配时,您可以标记该行
您需要按名称和日期对行进行排序,以便比较相邻日期。
select name, prevDate, prevCondition
from
(
select name, `date`, `value`, `condition`,
case when `date`<> @prevDate and `condition` <> @prevCondition
then 1
else 0
end as flag,
@prevDate := date AS prevDate,
@prevCondition := `condition` AS prevCondition
from table1, ( select @prevCondition:= NULL , @prevDate = NULL) as t
order by name, `date` )T
where T.flag =1