これに似たものを使用して、返したい月/年の値を置き換えることができます。
select b1.consumer_id,
sum(b1.reading - isnull(b2.reading, 0)) Total
from billing_history b1
left join billing_history b2
on b1.consumer_id = b2.consumer_id
and month(b2.reading_date) =12
and year(b2.reading_date) = 2012
where month(b1.reading_date) = 1
and year(b1.reading_date) = 2013
group by b1.consumer_id;
SQL FiddlewithDemoを参照してください。
month
との値を渡さずyear
に検索し、現在/前の月のみが必要な場合は、CTEを使用して次のようなものを使用できます。
;with cur as
(
select consumer_id,
reading,
month(getdate()) curMonth,
year(getdate()) curYear,
case when month(getdate()) = 1 then 12 else month(getdate()) -1 end preMonth,
case when month(getdate()) = 1 then year(getdate())-1 else year(getdate()) end preYear
from billing_history
where month(reading_date) = month(getdate())
and year(reading_date) = year(getdate())
)
select c.consumer_id,
sum(c.reading - isnull(pre.reading, 0)) TotalReading
from cur c
left join billing_history pre
on c.consumer_id = pre.consumer_id
and month(pre.reading_date) = c.preMonth
and year(pre.reading_date) = c.preYear
group by c.consumer_id
SQL FiddlewithDemoを参照してください
このバージョンでは、現在/前の月と年の両方の値が使用されます。CTE構文に精通していない場合は、次のように書くこともできます。
select c.consumer_id,
sum(c.reading - isnull(pre.reading, 0)) TotalReading
from
(
select consumer_id,
reading,
month(getdate()) curMonth,
year(getdate()) curYear,
case when month(getdate()) = 1 then 12 else month(getdate()) -1 end preMonth,
case when month(getdate()) = 1 then year(getdate())-1 else year(getdate()) end preYear
from billing_history
where month(reading_date) = month(getdate())
and year(reading_date) = year(getdate())
) c
left join billing_history pre
on c.consumer_id = pre.consumer_id
and month(pre.reading_date) = c.preMonth
and year(pre.reading_date) = c.preYear
group by c.consumer_id;
SQL FiddlewithDemoを参照してください。
クエリでわかるように、集計関数SUM()
とを使用GROUP BY
しましたconsumer_id
。私はあなたが顧客ごとに複数の読書をした場合にこれをしました。1か月に1回しか読み取れないことがわかっている場合は、集計を削除できます。