给定此示例数据集:

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

10-07 19:04
查看更多