2013-02-05 66 views
2

我有一張存儲每月結算信息的表格。找到同一個表中兩個字段之間的差異

CREATE TABLE [dbo].[billing_history](
[id] [numeric](18, 0) IDENTITY(1,1) NOT NULL, 
[reading_date] [date] NOT NULL, 
[reading] [numeric](18, 0) NOT NULL, 
[consumer_id] [int] NOT NULL) 

consumer_id是引用消費者詳細信息表的外鍵。

我想要的是從上個月的讀數中減去每個客戶當前的讀數。這將產生當前賬單。有任何想法嗎。

+0

什麼版本的sql server? – Taryn

+0

'前一個月的閱讀':對於一個客戶,每個月在billing_history中只有一個條目? –

+0

SQL Server 2008 – user2018756

回答

4

您可以使用類似於此,在那裏你會替換你想返回月/年的值的東西:

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

如果你不想在monthyear的值傳遞給搜索而您只需要電流/前一個月,那麼你可以使用使用類似以下內容的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。如果您爲每個客戶閱讀不止一次,我做到了這一點。如果你知道每個月只有一次閱讀,那麼你可以刪除聚合。

+0

它的工作表示感謝。 – user2018756

+0

我有另一張桌子,我有這個商業/家庭消費者的平板消耗的單位數量。例如國內消費者的50單位* 4和商業消費者的10。我如何將這些值與上述查詢的結果讀數相乘。 – user2018756

+0

@ user2018756:如果那是你不能應用這個答案的東西,你應該考慮問一個新的問題。我們傾向於在這個網站上保持簡單:一個問題,一個問題。 –

相關問題