Oracle SQL - 按周计算总和和组数据

时间:2014-08-12 08:34:31

标签: sql oracle aggregate-functions

我有与日期相关的记录:

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

我知道如何将它们总结为每一天,但我怎么能在一周之前总结它们呢?

3 个答案:

答案 0 :(得分:27)

试试这个

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


输出将是:

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

答案 1 :(得分:26)

您可以使用TRUNC功能将日期截断为一周的第一天。有a few ways of defining week。例如,如果您想要将星期的第一天视为星期一,则可以IW格式化,如下所示:

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

您也可以TO_CHAR充当“@Vignesh Kumer”的回答。

关键是你应该将同一周的日期截断为一个值。然后按值分组。就是这样。

答案 2 :(得分:0)

我想这也有帮助....

 /* 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