[英]how to calculate YTD (Year To Date) value in Oracle table
There is a table and its data looks like this:有一个表,它的数据是这样的:
year month v1 v2
2017 1 2 3
2017 2 4 5
... .. .. ..
2017 12 9 3
2018 1 1 3
2018 2 6 2
... .. .. ..
2018 12 2 2
the table has year, month, v1, v2 totally 4 fields, now I want a SQL to calculate YTD value for each row, the query result looks like this:该表有年,月,v1,v2 共 4 个字段,现在我想要一个 SQL 来计算每一行的 YTD 值,查询结果如下所示:
year month v1 v2 v1_YTD v2_YTD
2017 1 2 3 2 3
2017 2 4 5 6 8
... .. .. .. .. ..
2017 12 9 3 m1 n1
2018 1 1 3 1 3
2018 2 6 2 7 5
... .. .. .. .. ..
2018 12 2 2 m2 n2
YTD value, for example, calculate for February, then the YTD value = January + February, if the month is December, the YTD value should be the value for January + February + March +...+ December. YTD值,例如计算2月,那么YTD值=1月+2月,如果月份是12月,YTD值应该是1月+2月+3月+...+12月的值。
YTD value should not cross year. YTD 值不应跨年。
Is there a SQL can achieve this purpose?有没有SQL可以达到这个目的?
You could use analytic funtion SUM() OVER() 您可以使用分析功能SUM()OVER()
SELECT year, month, v1, v2,
SUM(v1) OVER (PARTITION BY year ORDER BY month) AS v1_ytd,
SUM(v2) OVER (PARTITION BY year ORDER BY month) AS v2_ytd
FROM table_name
ORDER BY year, month;
Not sure it will work in Oracle 10g and earlier. 不确定它将在Oracle 10g及更低版本中工作。 Try to add this field: 尝试添加此字段:
SUM(v1) OVER (PARTITION BY year ORDER BY month)
select
empid,
DOJ,
emp_salary,
sum(emp_salary) over (
partition by Extract(year from DOJ) order by DOJ asc
) as YTD
from emp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.