SQL查询: select the last record where a value went below a threshold

标签 sql database sybase

鉴于此示例数据集:

-----------------------------
| item   | date       | val |
-----------------------------
| apple  | 2012-01-11 |  15 |
| apple  | 2012-02-12 |  19 |
| apple  | 2012-03-13 |   7 |
| apple  | 2012-04-14 |   6 |
| orange | 2012-01-11 |  15 |
| orange | 2012-02-12 |   8 |
| orange | 2012-03-13 |  11 |
| orange | 2012-04-14 |   9 |
| peach  | 2012-03-13 |   5 |
| peach  | 2012-04-14 |  15 |
-----------------------------

我正在寻找针对每个项目的查询, 它将选择第一个日期,其中val低于CONST=10,之后又回到上面。在此示例中,将是:

-----------------------------
| item   | date       | val |
-----------------------------
| apple  | 2012-03-13 |   7 |
| orange | 2012-04-14 |   9 |
-----------------------------

在不使用游标的情况下这是否可能?我正在 Sybase 中寻找此内容。

如果没有游标就无法做到这一点,我可以用编程语言处理记录。然而,在这种情况下,由于在我的实际用例中,完整的历史记录非常长,所以我需要一个“合适的”查询,只选择“足够的”记录来计算我最终想要的记录:最新的记录,其中 val 跌破 CONST 下方,但没有回到上方。

最佳答案

这将返回详细的结果集。

select tablename.* from tablename
inner join 
(
    select tablename.item, min(tablename.[date]) as mindate 
                from tablename
        inner join (
                        select 
                             item, 
                             max([date]) lastoverdate 
                        from tablename 
                        where val>@const 
                        group by item
                               ) lastover
        on tablename.item = lastover.item
        and tablename.[date]> lastoverdate
    group by tablename.item
) below
    on tablename.item = below.item
    and tablename.date = below.mindate

关于SQL查询: select the last record where a value went below a threshold,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11228432/

相关文章:

java - OSWAP ESAPI 的 Sybase 编解码器

c# - 如何在 VS2012 中创建本地数据库缓存?

java - oracle关闭连接时如何抛出错误?

c++ - 如何在qt中修复 "No query Unable to fetch row"

PHP Exec 不工作,但命令本身工作正常

c - 将结构的大小作为 void 传递给函数

mysql - 更新后触发 - 复制到另一个表

mysql - 你的 SQL 语法有错误...在 'float)/CAST(rating_count AS float)) as average_rating from document' 附近

python - 如何处理南方(django)的重构?

c# - 如何有效地将 100s 到 1000s 的操作记录到数据库