如何检测特定值是不是包含在 MySQL 表窗口中

Posted

技术标签:

【中文标题】如何检测特定值是不是包含在 MySQL 表窗口中【英文标题】:How to detect whether specific value contains in MySQL table windows如何检测特定值是否包含在 MySQL 表窗口中 【发布时间】:2016-08-04 11:37:24 【问题描述】:

我的数据结构如下:

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)。

【问题讨论】:

【参考方案1】:

您可以通过以下方式获取每个属性的最后状态:

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)上建立索引。

【讨论】:

谢谢,稍作调整,这个查询就是我要找的! 调整是什么? 我认为 OPs 列是 as_of,因为此查询使用了 date @juergend @juergend 我将状态的描述性名称存储在查找表中,所以我加入了它,从中读取状态字符串。

以上是关于如何检测特定值是不是包含在 MySQL 表窗口中的主要内容,如果未能解决你的问题,请参考以下文章

在MYSQL中如何用一个字段的值替换另一个字段的值

MYSQL窗口函数-获取最后一个值

MySQL 检查表是不是仅包含此特定类型

如何使用窗口函数检查特定范围值是不是填充在 SQL 中?

SQL如何查找和删除MYSQL数据库中包含特定字符串的记录

sql 如何判断表中的某个字段是不是有某个值