2

给定这个示例数据集:

-----------------------------
| 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的最新记录没有回到它上面。

4

2 回答 2

3

这将返回详细的结果集。

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
于 2012-06-27T14:55:56.550 回答
1

对于 MySql:

select t.item, t.date1, t.val
from 
(
  select min(date) date1, item from tablename  t
  where not exists (select 1 from tablename where item = t.item 
                    and date1 > t.date1 and val >= 10)
and val < 10
  group by item
) a
inner join 
@t t
on a.item = t.item and a.date1 = t.date1

对于不同的数据库,例如 MS-sql 2005+:

select item, date, val from 
(
  select *, row_number() over (partition by item order by date) rn
  from tablename t
  where not exists (select 1 from @t where item = t.item and 
                    date > t.date and val >= 10)
  and val < 10
) a where rn = 1
于 2012-06-27T15:24:19.453 回答