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

各itemについて、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 に答える