Oracle SQL - 多次运行查询

时间:2013-03-06 23:18:04

标签: sql oracle

我有这个问题:

select '2012-Nov-01' As "Week_Of",
count(player_id) as cohort_size ,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 0 
    then player_id 
  end) as Day_0_Ret,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 1 
    then player_id 
  end) as Day_1_Ret,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 2
    then player_id 
  end) as Day_2_Ret,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 3
    then player_id 
  end) as Day_3_Ret
from player
where trunc(create_dtime) > To_Date('2012-Nov-01','yyyy-mon-dd')-7
and trunc(create_dtime) <= To_Date('2012-Nov-01','yyyy-mon-dd')
and world_flag != '1'
Which outputs:

Week_Of       Cohort_size    Day_0_Ret    Day_1 Ret    Day_2_Ret    Day_3_Ret
2012-Nov-01    2426           2426        1412         1349          1316

我希望能够为多组日期运行此查询,以便我的输出看起来像:

Week_Of       Cohort_size    Day_0_Ret    Day_1 Ret    Day_2_Ret    Day_3_Ret
2012-Nov-01    2426           2426        1412         1349          1316
2012-Nov-08    5106           2458        1945         1379          1248
2012-Nov-15    3580           1476        1412         1349          1146

而不是每次都在特定的一周内重新运行查询。这可能吗?

1 个答案:

答案 0 :(得分:4)

以下查询将您的逻辑更改为group by而不是where:

select to_char(max(create_dtime), 'yyyy-mm-dd') As "Week_Of",
       count(player_id) as cohort_size ,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 0 
    then player_id 
  end) as Day_0_Ret,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 1 
    then player_id 
  end) as Day_1_Ret,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 2
    then player_id 
  end) as Day_2_Ret,
count(case 
    when trunc(init_dtime)-trunc(create_dtime) >= 3
    then player_id 
  end) as Day_3_Ret
from player
where trunc(create_dtime) >= To_Date('2012-Nov-01','yyyy-mon-dd') - 6
and world_flag != '1'
group by trunc((trunc(create_dtime) - (To_Date('2012-Nov-01','yyyy-mon-dd') -  6))/7)
order by 1

它选择最后一个可用日期来描述一周......