如何在单个sql查询中计算增加或减少的百分比?
我有一张有以下结构的桌子如何在单个sql查询中计算增加或减少的百分比?,sql,sql-server,Sql,Sql Server,我有一张有以下结构的桌子 Event Id | Year ------------------- 1xxxxx | 2014 2xxxxx | 2014 3xxxxx | 2014 4xxxxx | 2014 5xxxxx | 2014 6xxxxx | 2015 7xxxxx | 2015 8xxxxx | 2015 我需要找出与2014年相比,2
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。因此,与2014年相比,2015年的事件增加百分比为3-5*100/5=-40.0%。如果我理解正确,您可以通过条件聚合实现这一点:
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;
如果我理解正确,您可以通过条件聚合来实现这一点:
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;
以下是通用声明,不仅限于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
Fiddle以下是通用声明,不仅限于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
Fiddle请编辑您的问题并提供示例结果。当我们计算2014年发生的事件数时,它等于5,而2015年则等于3。所以增加或减少的百分比是3-5*100/3=-66.6。你为什么要用2015作为分母?对不起,我错了。。2014年的值应为分母。请编辑您的问题并提供样本结果。当我们计算2014年发生的事件数时,它等于5,2015年相同为3。所以增加或减少的百分比是3-5*100/3=-66.6。你为什么要用2015作为分母?对不起,我错了。。2014年的价值应该是分母