2015-04-19 28 views
1

我有以下結構如何獲得計算單個sql查詢的增加或減少百分比?

Event Id | Year 
------------------- 
1xxxxx  | 2014 
2xxxxx  | 2014 
3xxxxx  | 2014 
4xxxxx  | 2014 
5xxxxx  | 2014 
6xxxxx  | 2015 
7xxxxx  | 2015 
8xxxxx  | 2015 

我需要找到的事件數量增加的百分比在2015年發生的事情相比,2014年,我需要使用一個SQL查詢來發現它的表。我怎樣才能做到這一點?

例如,如果我們將2014年發生的事件數量等於5,2015年也是3,那麼2015年事件與2014年相比的增長百分比爲((3-5)* 100)/5 = -40.0%。

+1

請編輯您的問題並提供樣品結果。 –

+0

以2014年發生的事件數量爲例,2015年發生的事件數量爲5,2015年發生的事件數量也是3,因此百分比增減爲((3-5)* 100)/ 3 = -66.6。 – geo

+0

你爲什麼要用2015作爲分母? –

回答

1

,如果我理解正確的話,你可以使用條件的聚集做到這一點:

select sum(case when year = 2014 then 1 else 0 end) as ev_2014, 
     sum(case when year = 2015 then 1 else 0 end) as ev_2015, 
     (sum(case when year = 2015 then 100.0 else 0 end) 
     sum(case when year = 2014 then 1.0 end) 
     ) - 100.0 as percent_change  
from table t; 
2

這裏是通用的聲明,不侷限於僅2014年和2015年:

CREATE TABLE test (id INT, year int); 

Insert into test values 
(1, 2014), 
(2, 2014), 
(3, 2014), 
(4, 2014), 
(5, 2014), 
(6, 2015), 
(7, 2015), 
(8, 2015), 
(9, 2016) 

;with cte as(
    select year y, count(*) c from test 
    group by year) 
select c1.y, 
     ca.y, 
     (c1.c - ca.c)*100.0/ca.c inc, 
     (ca.c - c1.c)*100.0/c1.c dec 
from cte c1 
cross apply(select top 1 * from cte c2 where c2.y < c1.y order by c2.y desc)ca 

輸出:

y  y  inc     dec 
2015 2014 -40     66.666666666666 
2016 2015 -66.666666666666  200 

小提琴http://sqlfiddle.com/#!6/9e1cf/3