我有一张结构如下的桌子
Event Id | Year
-------------------
1xxxxx | 2014
2xxxxx | 2014
3xxxxx | 2014
4xxxxx | 2014
5xxxxx | 2014
6xxxxx | 2015
7xxxxx | 2015
8xxxxx | 2015 我需要找到与2014年相比,2015年发生的事件数量增加的百分比。我需要使用一个SQL查询找到它。我怎样才能做到这一点?
例如,以2014年发生的事件数为例,它等于5起,而2015年则是3起。因此,2015年与2014年相比,事件增长的百分比是(3-5)*100/5= -40.0 %。
发布于 2015-04-19 15:22:15
如果我正确理解,您可以使用条件聚合来完成这一任务:
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;发布于 2015-04-19 17:15:30
以下是不限于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
https://stackoverflow.com/questions/29731722
复制相似问题