Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL - Sum and group data by week

Tags:

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?`

like image 818
royskatt Avatar asked Aug 12 '14 08:08

royskatt


People also ask

How to get weekly data in oracle sql?

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.

Can we use sum with GROUP BY?

SUM is used with a GROUP BY clause. The aggregate functions summarize the table data. Once the rows are divided into groups, the aggregate functions are applied in order to return just one value per group. It is better to identify each summary row by including the GROUP BY clause in the query resulst.

Can we calculate week numbers in Oracle?

How to get the week number from a date. To get the ISO week number (1-53) from a date in the column datecol , use SELECT TO_CHAR( datecol , 'IW') FROM … . To get the corresponding four-digit year, use SELECT TO_CHAR( datecol , 'IYYY') FROM … . Read more about TO_CHAR() in the Oracle manual.

What is IW in Oracle?

The 'WW' function returns the week number based on 1-7 days (one being the first week of the year). Therefore the first seven days of the year will be regarded as the first week. There is another function named 'IW', which is based on a Saturday to Sunday days format. For example, January 6, 1998 is a Tuesday.


2 Answers

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.

like image 106
ntalbs Avatar answered Sep 20 '22 03:09

ntalbs


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      | +-----+-------+--------+ 
like image 28
Vignesh Kumar A Avatar answered Sep 19 '22 03:09

Vignesh Kumar A