如何使用pl / sql按周计算记录?

时间:2011-01-26 15:28:50

标签: oracle plsql

我在Oracle中有一个查询报告,如下所示:

SELECT TRUNC (created_dt) created_dt
    ,  COUNT ( * ) AllClaims
    ,  SUM(CASE WHEN filmth_cd in ('T', 'C') THEN 1 ELSE 0 END ) CT
    ,  SUM(CASE WHEN filmth_cd = 'W' THEN 1 ELSE 0 END ) Web 
    ,  SUM(CASE WHEN filmth_cd = 'I' THEN 1 ELSE 0 END ) Icon 
FROM claims c
WHERE c.clsts_cd NOT IN ('IN', 'WD')
   AND  TRUNC (created_dt) between 
    to_date('1/1/2006', 'dd/mm/yyyy') AND 
    to_date('1/1/2100', 'dd/mm/yyyy')
GROUP BY TRUNC (created_dt)
ORDER BY TRUNC (created_dt) DESC;

它会返回如下数据:

Create_Dt  AllClaims   CT    Web    Icon
1/26/2011  675         356   285    34
1/25/2011  740         322   379    39
...

我需要的是一个结果集,它将所有每日值汇总为每周值。我是PL / SQL的新手,不知道从哪里开始。

2 个答案:

答案 0 :(得分:4)

这样的东西
SELECT TRUNC (created_dt, 'IW') created_dt
    ,  COUNT ( * ) AllClaims
    ,  SUM(CASE WHEN filmth_cd in ('T', 'C') THEN 1 ELSE 0 END ) CT
    ,  SUM(CASE WHEN filmth_cd = 'W' THEN 1 ELSE 0 END ) Web 
    ,  SUM(CASE WHEN filmth_cd = 'I' THEN 1 ELSE 0 END ) Icon 
FROM claims c
WHERE c.clsts_cd NOT IN ('IN', 'WD')
   AND  TRUNC (created_dt) between 
    to_date('1/1/2006', 'dd/mm/yyyy') AND 
    to_date('1/1/2100', 'dd/mm/yyyy')
GROUP BY TRUNC (created_dt, 'IW')
ORDER BY TRUNC (created_dt, 'IW') DESC;

将根据ISO周的第一天汇总数据。

答案 1 :(得分:1)

这是一个我经常使用的简单示例:

SELECT
 TO_CHAR(created_dt,'WW'),
 max(created_dt),
 COUNT(*)
from MY_TABLE
group by
  TO_CHAR(created_dt,'WW');

to_char(created_dt,'WW')创建组,max(created_dt)显示一周的最后一天。如果要显示一周的第一天,请使用min(created_dt)。