Oracle SQL - Sum and group data by week

本秂侑毒 提交于 2019-11-27 17:21:30

问题


I have records related to dates:

DATE         AMOUNT
16.03.2013   3
16.03.2013   4
16.03.2013   1
16.03.2013   3
17.03.2013   4
17.03.2014   3

I know how to sum them up for each day, but how could I sum them up by week?`


回答1:


Try this

SELECT to_char(DATE - 7/24,'IYYY'), to_char(DATE - 7/24,'IW'),SUM(AMOUNT)
FROM YourTable
GROUP BY to_char(DATE - 7/24,'IYYY'), to_char(DATE - 7/24,'IW')

FIDDLE DEMO


Output would be:

+-----+-------+--------+
|YEAR | WEEK  | AMOUNT |
+-----+-------+--------+
|2013 | 11    | 18     |
|2013 | 13    | 3      |
+-----+-------+--------+



回答2:


You can use TRUNC function to truncate date to the first day of week. There are a few ways of defining week. For example, if you want to treat that the first day of week is Monday, you can IW format, like this:

select trunc(date, 'IW') week, sum(amount)
from YourTable
group by trunc(date, 'IW');

You can also TO_CHAR function as the "@Vignesh Kumer"'s answer.

The point is that you should truncate the date in the same week into one value. Then group by the value. That's it.




回答3:


I guess this would help as well....

 /* Weekly sum of values */
 SELECT SUM( Amount ) as Sum_Amt, 
 DATEPART (wk, Date) as WeekNum
 FROM databse_name.table_name
 GROUP BY DATEPART (wk, Date)
 ORDER BY WeekNum

 /* Monthly sum of values */
 SELECT SUM( Amount ) as Sum_Amt, 
 DATEPART (mm, Date) as MonNum
 FROM databse_name.table_name
 GROUP BY DATEPART (mm, Date)
 ORDER BY MonNum


来源:https://stackoverflow.com/questions/25259633/oracle-sql-sum-and-group-data-by-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!