您可以使用類似於此,在那裏你會替換你想返回月/年的值的東西:
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 Fiddle with Demo。
如果你不想在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 Fiddle with Demo
該版本獲取當前/上一個月份和年份的值。如果你不熟悉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 Fiddle with Demo。
正如您在我的查詢中看到的,我使用consumer_id
上的聚合函數SUM()
和GROUP BY
。如果您爲每個客戶閱讀不止一次,我做到了這一點。如果你知道每個月只有一次閱讀,那麼你可以刪除聚合。
什麼版本的sql server? – Taryn
'前一個月的閱讀':對於一個客戶,每個月在billing_history中只有一個條目? –
SQL Server 2008 – user2018756