2016-08-04 40 views
2

我的數據結構,如:如何檢測特定的值是否包含在MySQL表窗口

id  property_id  status  tran_id  as_of 
1  1    sold  1111   2015-04-01  
2  1    listed  1111   2015-01-05 
3  1    pending  1111   2015-01-02 

7  2    listed  2211   2014-09-01 
8  2    delisted 2211   2014-06-01 
9  2    listed  2211   2014-04-01 
10  2    delisted 2211   2014-01-01 
11  2    sold  2211   2010-01-01 

12  3    sold  6661   2015-08-01  
13  3    pending  6661   2015-04-05 
14  3    listed  6661   2015-04-01 
... 

我想是能夠檢測特定屬性是否被出售(即最後狀態時order by as_of asc不是sold)。因此,對於我的情況,屬性1和3已售出,而2不是。我知道如何使用MS SQL Server的OVER()PARTITION BY(),但現在我正在使用MySQL,並且我完全停留在它上(我不知道MySQL和MSSQL)。

回答

2

您可以通過執行獲得每個屬性的最後狀態:

select t.*, 
     (case when status = 'sold' then 1 else 0 end) as is_sold 
from t 
where t.as_of = (select max(t2.as_of) 
       from t t2 
       where t2.property_id = t.property_id 
       ); 

如果你有大量的數據,則建議在t(property_id, date)的索引。

+0

謝謝,只需稍作調整,這個查詢就是我正在尋找的! –

+0

而調整是? –

+0

我認爲OPs列是'as_of',因爲這個查詢使用了'date' @juergend – e4c5

相關問題