我需要按周进行报告,但我的周数应从月的第一天开始
这是我的样本数据:
report_date Vol
01 nov 2014 23
03 nov 2014 34
16 nov 2014 56
30 nov 2014 44
期望的输出
Week no Vol
1 57
2 56
3 0
4 44
希望其明确
谢谢
答案 0 :(得分:1)
由于您所需的输出包括"零"行也是如此,假设您希望此报告在多个月内也可以使用:
WITH sample_data AS
(SELECT DATE '2014-11-01' AS report_date, 23 AS vol FROM DUAL
UNION ALL SELECT DATE '2014-11-03', 34 FROM DUAL
UNION ALL SELECT DATE '2014-11-16', 56 FROM DUAL
UNION ALL SELECT DATE '2014-11-30', 44 FROM DUAL)
,weeks AS
(SELECT report_month
,TO_CHAR(ROWNUM) AS week_no
FROM (SELECT DISTINCT
TRUNC(report_date,'MM') AS report_month
FROM sample_data)
CONNECT BY LEVEL <= TO_NUMBER(TO_CHAR(LAST_DAY(report_month),'W')))
SELECT TO_CHAR(weeks.report_month,'Month') AS "Month"
,weeks.week_no AS "Week no"
,NVL(sum(sample_data.vol),0) AS "Vol"
FROM weeks
LEFT JOIN sample_data
ON weeks.report_month = TRUNC(report_date,'MM')
AND weeks.week_no = to_char(report_date,'W')
GROUP BY weeks.report_month, weeks.week_no ORDER BY 1,2;
我们使用LAST_DAY
函数确定源数据每个月的周数,并且我们执行分层查询(CONNECT BY LEVEL <= n
)以在每个月中为每周生成一行。
预期输出应为:
Month Week no Vol
======== ======= ===
November 1 57
November 2 0
November 3 56
November 4 0
November 5 44
答案 1 :(得分:0)
select to_char(report_date, 'W'), sum(vol)
from your_table
group by to_char(report_date, 'W');
W 每周(1-5)周,第1周从第1天开始 月份,并在第七个结束。