如何检测特定值是否包含在MySQL table windows
How to detect whether specific value contains in MySQL table windows
我的数据结构如下:
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 服务器的 OVER()
和 PARTITION BY()
来做到这一点,但现在我正在使用 MySQL 并且我完全坚持它(我不知道 MySQL 以及 MSSQL)。
您可以通过以下方式获取每个 属性 的最后状态:
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)
上建立索引。
我的数据结构如下:
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 服务器的 OVER()
和 PARTITION BY()
来做到这一点,但现在我正在使用 MySQL 并且我完全坚持它(我不知道 MySQL 以及 MSSQL)。
您可以通过以下方式获取每个 属性 的最后状态:
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)
上建立索引。