2014-12-02 48 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)的索引。