2015-11-06 90 views
0

我正在嘗試計算兩個不同年份的月數,以便爲每個月總計一個年度至今和AVG的小型財務報告。例如,假設一位客戶去年四月加入了我們,去年他們將有9個月的收費,而今年11月。對於報告的這一部分,這是針對這些收費進行的調整。不是所有的月份都會有調整,但所有的月份(9和11)都會收費。兩年期間的兩次日期計算

enter image description here

有了這個例子中這些都是每個月的調整。我可以獲得2014年4月的最低交易日期,以幫助我計算2014年的AVG。以上是不正確的。這應該是YTD/3,而不是YTD/9。但是我可以計算一下,但是我不能在2015年,YTD/11上運行。

我有什麼權利現在(簡體版)

declare @StartDate DATETIME = getdate() 
, @MinDate DATETIME 

select @MinDate = min(txndate) 
from dbo.txn 

select d.year, 
     d.jan, 
     d.feb, 
     etc... 
     d.YTD/--how to calculate here?? 
from .... 

我似乎不能放在一起就不同年份和計算的情況下聲明。任何想法不勝感激。

+0

這是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

回答

0
create table #txn 
(
year smallint, 
Jan money, Feb money, Mar money, Apr money, 
May money, Jun money, Jul money, Aug money, 
Sep money, Oct money, Nov money, Dec money 
) 

insert #txn 
values(2014,null,null,null,null,null,null,null,null,null,95,36.89,95), 
(2015,100,6389.27,null,null,1035,257,669.05,0,null,514,2791.01,null) 


select year, month, money 
from #txn 
unpivot 
(
    money 
    for month in (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) 
) unpivotalias 

;with aggregate as 
(
select year, sum(money) as 'YTD', sum(money)/count(*) as 'AVG' 
from #txn 
unpivot 
(
    money 
    for month in (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) 
) unpivotalias 
group by year 
) 
select t.year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec,YTD,AVG 
from #txn as t join aggregate as a on t.year = a.year 
order by t.year