data, ID, Value, Exp1
201101, 1, 2
201202, 1, 3
201303, 1, 4
201101, 2, 2
201202, 2, 3
201303, 2, 4
201304, 2, 5
201305, 2, 6
201306, 2, 7
201307, 2, 8
201308, 2, 9
201309, 2, 10
201310, 2, 11
201311, 2, 12
201312, 2, 13
我必须将Exp1的值计算为
代表ID=2
。 Exp1= (sum of value from 201307 to 201312)/6-(sum of value from 201301 to 201306)/6
有些ID可能没有所有月份的值,有些可能只有一个值。
这可能在SQL
吗?
:Exp1 =(13 + 12 + 11 + 10 + 9 + 8)/ 6-(7 + 6 + 5 + 4 + 3 + 2)/ 6
表示ID 1:Exp1 =(0 + 0 + 0 + 0 + 0 + 0 + 0 + 0)/ 6-(2 + 3 + 4 + 0 + 0 + 0)/ 6
必须为所有IDS
完成此操作答案 0 :(得分:2)
select
ID,
sum(
case
when YRMO between 201307 and 201312 then value
else 0
end)/6
- sum(
case
when YRMO between 201301 and 201306 then value
else 0
end)/6 as EXP1
from TABLE
group by ID;
答案 1 :(得分:0)
select
id,
sum(value) / 6 exp1
from (
select
id,
case when YRMO between '201301' and '201306' then -value else value end value
from `table`
where YRMO between '201301' and '201312'
) q
group by id