说白了就是计算一年中有多少个星期日,多少个星期一,多少个星期二……
思路大致如下:
1、生成一年内的所有日期
2、设置日期格式,得到每个日期对应为星期几。
3、计算周内日期分别有多少个。
SQL> with x as
2 (
3 select level lvl from dual
4 connect by level<=(add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y'))
5 )
6 select to_char(trunc(sysdate,'y')+lvl-1,'DAY'),count(*)
7 from x
8 group by to_char(trunc(sysdate,'y')+lvl-1,'DAY');
TO_CHAR(TRUNC(SYSDATE,'Y')+ COUNT(*)
--------------------------- ----------
THURSDAY 53
SATURDAY 52
TUESDAY 52
SUNDAY 52
WEDNESDAY 52
MONDAY 52
FRIDAY 52
7 rows selected.
注意,在这里level的列别名lvl是必须的,如果不加的话会出错。
SQL> with x as
2 (
3 select level from dual
4 connect by level<=(add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y'))
5 )
6 select to_char(trunc(sysdate,'y')+level-1,'DAY'),count(*)
7 from x
8 group by to_char(trunc(sysdate,'y')+level-1,'DAY');
from x
*
ERROR at line 7:
ORA-01788: CONNECT BY clause required in this query block
这个时候在第六行和第八行中的level系统会认为是下面这个select的,而不是上面select中的level,因此提示缺失connect by子句。
如果是oracle8i或较早的版本,不能使用connect by的话,可是通过基干表来完成相关内容。
SQL> create table t500(id number);
Table created.
SQL> begin
2 for i in 1..500 loop
3 insert into t500 values(i);
4 end loop;
5 end;
6 /
PL/SQL procedure successfully completed.
SQL> select id from t500 where rownum<10; --验证一下看数据插入到表中没有
ID
----------
1
2
3
4
5
6
7
8
9
9 rows selected.
SQL> select to_char(trunc(sysdate,'y')+rownum-1,'DAY'),count(*)
2 from t500
3 where rownum<=(add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y'))
4 group by to_char(trunc(sysdate,'y')+rownum-1,'DAY');
TO_CHAR(TRUNC(SYSDATE,'Y')+ COUNT(*)
--------------------------- ----------
THURSDAY 53
SATURDAY 52
TUESDAY 52
SUNDAY 52
WEDNESDAY 52
MONDAY 52
FRIDAY 52
7 rows selected.