我在db2中有一个包含列的表:
PK (varchar)
COLUMN1 (VARCHAR)
..
..
..
CREATION_TIMESTAMP (TIMESTAMP)
我需要根据每五天一次的自定义日期范围计算。 我将从“2014年12月1日”开始,然后根据5天的差距对我的计数进行分组:
group 1 : Dec 1 to Dec 5
group 2 : Dec 6 to Dec 10
...
...
and so on.
如果我必须按预先定义的范围进行分组,这很容易;我可以简单地做
select count(*), week(CREATION_TIMESTAMP)
from MYTABLE
group by week(CREATION_TIMESTAMP);
类似于日,月,年等。但是有没有办法定义上面提到的自定义范围?
答案 0 :(得分:1)
您需要一个将creation_time映射到所需间隔的函数。类似的东西:
select monthname(CREATION_TIMESTAMP)
, day(CREATION_TIMESTAMP) + 1 - mod(day(CREATION_TIMESTAMP),5)
, count(1)
from ...
group by monthname(CREATION_TIMESTAMP)
, day(CREATION_TIMESTAMP) + 1 - mod(day(CREATION_TIMESTAMP),5)
示例:
with t(n) as ( values date('2014-12-01')
union all
select n + 1 day from t
where n < '2014-12-20'
) select distinct day(n) + 1 - mod(day(n),5), day(n) + 5 - mod(day(n),5)
from t;
1 2
----------- -----------
SQL0347W The recursive common table expression "LELLE.T" may contain an
infinite loop. SQLSTATE=01605
1 5
6 10
11 15
16 20
21 25
编辑:扩展示例
with t(n) as (
values date('2014-12-01')
union all
select n + 1 day
from t where n < '2014-12-20'
)
select day(n)
, mod(day(n),5)
, day(n) + 1 - mod(day(n),5)
from t
1 1 1
2 2 1
3 3 1
4 4 1
5 0 6
6 1 6
7 2 6
8 3 6
9 4 6
10 0 11
11 1 11
12 2 11
13 3 11
14 4 11
15 0 16
16 1 16
17 2 16
18 3 16
19 4 16
20 0 21