2016-12-30 4 views
0

私は売上テーブルを持ち、2つの異なる日付範囲を持っています。 つまり、合計販売額は(2016-12-21 - 2016-12-30) is 100で、期間は(2016-12-11 - 2016-12-20) is 85です。 私が欲しい結果は1つのクエリで異なる2つの日付範囲のレコードを取得します

100 (sales of 2016-12-21 - 2016-12-30), 85 (sales of 2016-12-11 - 2016-12-20), 15 (difference of both periods)です。

私は何を考えていることは

select *, (a.sales - b.sales) as diff 
from (select id, sum(sales) as sales from salestable where date >= '2016-12-21' and date <= '2016-12-30') a 
join (select id, sum(sales) as sales from salestable where date >= '2016-12-11' and date <= '2016-12-20') b 
on a.id = b.id; 

でこれを行うには、他のより良い方法はありますか?

答えて

1

あなたは条件付き集計使用することができます:あなたはidによって、全体の合計をしたい場合は、あなたを含めることによって示唆されているように(

select sum(case when date >= '2016-12-21' and date <= '2016-12-30' then sales else 0 
      end) as sales_a, 
     sum(case when date >= '2016-12-11' and date <= '2016-12-20' then sales else 0 
      end) as sales_b, 
     sum(case when date >= '2016-12-21' and date <= '2016-12-30' 
       then sales else 0 
       when date >= '2016-12-11' and date <= '2016-12-20' 
       then -sales 
       else 0 
      end) as sales_diff 
from salestable; 

id)、次にをselectに追加し、group by idを追加します。

0

次のような条件付きの合計を行うためにcaseを使用することができます。

select id, 
    sum_21_to_30, 
    sum_11_to_20, 
    sum_21_to_30 - sum_11_to_20 diff 
from (select id, 
    sum(case when date >= '2016-12-21' and date <= '2016-12-30' then sales else 0 end) sum_21_to_30, 
    sum(case when date >= '2016-12-11' and date <= '2016-12-20' then sales else 0 end) sum_11_to_20 
from table group by id) t; 
関連する問題