鉴于此示例数据集:
-----------------------------
| 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/