作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
给定这个示例数据集:
-----------------------------
| 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 |
-----------------------------
我正在寻找针对每个项目的查询,它将选择第一个 date,其中 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/
我是一名优秀的程序员,十分优秀!