SQL如何按日期范围分组

时间:2011-09-30 22:55:02

标签: sql group-by oracle-sqldeveloper

有人可以帮我解决一系列日期吗?

现在我的查询类似于

    Select date, count(x)
    from data
    group by date

返回看起来像这样的结果

    2011/1/1   10
    2011/1/2   5
    2011/1/3   8
    2011/1/4   3

等...

但我想每2天计算一次,以便数据看起来像这样

    2011/1/1   15
    2011/1/3   11

任何想法??

由于

2 个答案:

答案 0 :(得分:2)

您可以通过转换为数字整数值并将其缩小为偶数来将日期标准化为2的组。一个简单的方法是val / 2 * 2,因为第一个/ 2将被截断任何小数位(只要val的类型是整数!),{{1除了标准化为偶数之外,它将返回原始值。以下是使用CTE数据源对结果进行标准化和分组的示例:

* 2

输出:

;with Data as ( 
    select '1/1/2011' as [date], 1 as x union
    select '1/1/2011' as [date], 2 as x union
    select '1/1/2011' as [date], 3 as x union
    select '1/1/2011' as [date], 4 as x union
    select '1/1/2011' as [date], 5 as x union
    select '1/1/2011' as [date], 6 as x union
    select '1/1/2011' as [date], 7 as x union
    select '1/1/2011' as [date], 8 as x union
    select '1/1/2011' as [date], 9 as x union
    select '1/1/2011' as [date], 10 as x union
    select '1/2/2011' as [date], 11 as x union
    select '1/2/2011' as [date], 12 as x union
    select '1/2/2011' as [date], 13 as x union
    select '1/2/2011' as [date], 14 as x union
    select '1/2/2011' as [date], 15 as x union
    select '1/3/2011' as [date], 16 as x union
    select '1/3/2011' as [date], 17 as x union
    select '1/3/2011' as [date], 18 as x union
    select '1/3/2011' as [date], 19 as x union
    select '1/3/2011' as [date], 20 as x union
    select '1/3/2011' as [date], 21 as x union
    select '1/3/2011' as [date], 22 as x union
    select '1/3/2011' as [date], 23 as x union
    select '1/4/2011' as [date], 24 as x union
    select '1/4/2011' as [date], 25 as x union
    select '1/4/2011' as [date], 26 as x
)
Select
    cast(cast(cast(Date as datetime) as integer) / 2 * 2 as datetime) as date,
    count(x)
from data
group by cast(cast(Date as datetime) as integer) / 2 * 2

答案 1 :(得分:1)

Select floor((date - trunc(date,'MM')) / 2), count(x)
  from data
 group by floor((date - trunc(date,'MM')) / 2)