いくつかの顧客 ID と取引日があるとします。
ID DATE
1 OCT 1
1 OCT 2
1 OCT 3
1 OCT 31
私が欲しいのは、前の取引日を示す列と、次の取引日を示す別の列です (以下を参照)。
ID DATE1 DATE2
1 OCT 1 OCT 2
1 OCT2 OCT3
1 OCT 3 OCT 31
ここで、ID
は INTEGER で、DATE
は DATE です。
どうすればこれを達成できますか?
Most dialects of SQL support the ANSI standard window functions, including lead()
:
select t.*
from (select t.*,
lead(date) over (partition by id order by date) as next_date
from t
) t
where next_date is not null;
For databases that don't support this functionality, you can do something similar with a subquery.
使用しているデータベースに関係なく、結果を 2 回選択するだけで、どちらも行番号を示す列挙子列を使用して (たとえば、T-SQL では ROW_NUMBER()) の使用方法を参照し、これら 2 つの選択を結合するだけです。 a.enumerator = b.enumerator - 1