既存のクエリ結果が必要な場合は、クエリを次のように書き直します。
select t1.id,
CONVERT(VARCHAR,t1.dt,103) date_1,
CONVERT(VARCHAR,t2.dt,103) date_2,
t1.hotel,
t1.price price_1,
t2.price price_2,
t2.price - t1.price difference,
((t2.price - t1.price)/t1.price)*100 as Diff_percentage
from test t1
join (select max(dt) maxDt from test) d
on t1.dt = d.maxDt-1
join test t2
on t2.hotel = t1.hotel
and t2.dt = d.maxDt
元のクエリを拡張して、行が欠落しているホテルを含めるには:
select t1.id,
CONVERT(VARCHAR,t1.dt,103) date_1,
CONVERT(VARCHAR,t2.dt,103) date_2,
h.hotel,
t1.price price_1,
t2.price price_2,
t2.price - t1.price difference,
((t2.price - t1.price)/t1.price)*100 as Diff_percentage
from (select distinct hotel from test) h
cross join (select max(dt) maxDt from test) d
left join test t1
on t1.hotel = h.hotel
and t1.dt = d.maxDt-1
left join test t2
on t2.hotel = h.hotel
and t2.dt = d.maxDt
上記のクエリは、SELECT DISTINCTサブクエリを置き換えるために、正規化されたHOTELテーブル(ホテルごとに1行)を使用するとはるかに効率的です。
要求された結果を取得するには、次を使用します。
select count(case when (t2.price-t1.price) < 0 then 1 end) decrease_count,
count(case when (t2.price-t1.price) > 0 then 1 end) increase_count,
count(case when (t2.price-t1.price) = 0 then 1 end) same_count,
count(distinct t1.hotel) - count(case when (t2.price-t1.price) is not null then 1 end) unavailable_count
from test t1
left join (select max(dt) maxDt from test) d
on t1.dt = d.maxDt-1
left join test t2
on t2.hotel = t1.hotel
and t2.dt = d.maxDt
繰り返しますが、上記は正規化されたHOTELテーブルを使用するとより効率的になります。前のクエリと同じようにクエリを再構築します。MAX日付クエリにクロス結合されたHOTELから選択し、2つの日付のデータに対してTESTテーブルに2回外部結合します。次に、差分計算がNULLである行の数をカウントして、使用できないカウントをより直接的に測定できます。
これは、すべてのクエリのSQL Fiddleと、いくつかの拡張テストデータです。