sql統計時間出現斷點的相關情況

OmarChina發表於2007-05-20

Question:
有一表,其資料如下:
 時間            數
2006/01/01          xxx.xx
2006/01/02           xxx.xx
2006/01/03          xxx.xx
2006/01/04          xxx.xx
    ..........         ......
統計結果要如下:
   期間             sum數
2006/01/01(星期五)~2006/01/03(星期日)      xxx.xx
2006/01/04(星期一)~2006/01/10(星期日)      xxx.xx
...... ....

[@more@]

Answer:按自然的星期來統計SQL> select * from t;
LOGDATE RN
----------- ----
2006-11-22 1
2006-11-23 2
2006-11-24 3
..........
2006-12-19 28
2006-12-20 29

29 rows selected

SQL>
SQL> SELECT TO_CHAR(TRUNC(MIN(B.LOGDATE)), 'YYYY-MM-DD') || '(' ||
2 TO_CHAR(TRUNC(MIN(B.LOGDATE)), 'Day') || ')~' ||
3 TO_CHAR(TRUNC(MAX(B.LOGDATE)), 'YYYY-MM-DD') || '(' ||
4 TO_CHAR(TRUNC(MAX(B.LOGDATE)), 'Day') || ')' AS weekday,
5 C.TOTAL AS total
6 FROM T B,
7 (SELECT DECODE(TO_CHAR(A.LOGDATE, 'd'),
8 1,
9 TO_CHAR(A.LOGDATE, 'WW') - 1,
10 TO_CHAR(A.LOGDATE, 'WW')) AS WEEKDAY,
11 SUM(A.RN) AS TOTAL
12 FROM T A
13 GROUP BY DECODE(TO_CHAR(A.LOGDATE, 'd'),
14 1,
15 TO_CHAR(A.LOGDATE, 'WW') - 1,
16 TO_CHAR(A.LOGDATE, 'WW'))) C
17 WHERE DECODE(TO_CHAR(B.LOGDATE, 'd'),
18 1,
19 TO_CHAR(B.LOGDATE, 'WW') - 1,
20 TO_CHAR(B.LOGDATE, 'WW')) = C.WEEKDAY
21 GROUP BY C.TOTAL
22 ORDER BY weekday
23 /

WEEKDAY TOTAL
------------------------------------- ----------
2006-11-22(星期三)~2006-11-26(星期日) 15
2006-11-27(星期一)~2006-12-03(星期日) 63
2006-12-04(星期一)~2006-12-10(星期日) 112
2006-12-11(星期一)~2006-12-17(星期日) 161
2006-12-18(星期一)~2006-12-20(星期三) 84

這個方法比較優越:
SELECT * FROM TEST02;
TIME1 NUM1
---------- ----------
23-11月-06 1
24-11月-06 2
25-11月-06 3
.........
25-2月 -07 95
26-2月 -07 96
27-2月 -07 97

TIME1 NUM1
---------- ----------
28-2月 -07 98
01-3月 -07 99
02-3月 -07 100
已選取 100 個資料列.
SQL> SELECT TO_CHAR(NEXT_DAY(TIME1, 2), 'YYYY/MM/DD'), SUM(NUM1)
2 FROM TEST02
3 GROUP BY TO_CHAR(NEXT_DAY(TIME1, 2), 'YYYY/MM/DD');

TO_CHAR(NE SUM(NUM1)
---------- ----------
2006/11/27 10
2006/12/04 56
2006/12/11 105
2006/12/18 154
2006/12/25 203
2007/01/01 252
2007/01/08 301
2007/01/15 350
2007/01/22 399
2007/01/29 448
2007/02/05 497
2007/02/12 546
2007/02/19 595
2007/02/26 644
2007/03/05 490
已選取 15 個資料列.

主要是巧妙使用了NEXT_DAY函式。

select to_char(min(time1),'yyyy-mm-dd')||'('||to_char(min(time1),'day')||')'||'~'||to_char(max(time1),'yyyy-mm-dd')||'('||to_char(max(time1),'day')||')',sum(num1)
from test02
group by trunc(next_day(time1,2));

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9925929/viewspace-915612/,如需轉載,請註明出處,否則將追究法律責任。

相關文章