2014-12-02 31 views
0

我发布一个更新的问题上mysql query, return rows when condition is satisfiedMySQL查询,以确定状态的变化

感谢那些谁帮助...

好吧,我走在这第二个尝试,因为我搞砸了我原来的问题。我已更正日期格式以匹配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 

现在我想看看我是否可以修改我的查询只返回的状态改变。我查看了提供的答案,但是我将它们与原始查询结合起来以产生期望的结果。感谢已经给予的帮助,并且我非常抱歉,第一次没有正确地解答我的问题。

+1

我希望这些日期是在'DATE'列。 – tadman 2014-12-02 21:04:18

+0

是的。当他们是,让我们知道 – Strawberry 2014-12-02 21:08:10

+0

是的,所以我应该写他们为YYYY-MM-DD – tman 2014-12-02 21:13:02

回答

1

你可以使用MySQL变量来做到这一点。

每当日期不匹配和条件不匹配,你可以标记该行

你需要使相邻的日期进行比较,以行的名字和日期排序。

SQL Fiddle

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 
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)的索引。