2016-04-19 39 views
0

我有以下查詢,這讓我在7天的時間內識別次數的個別行爲進行不少於$ 1,000的交易正是兩次:自動重新運行具有不同參數的SQL查詢

select count(*) 
from (

select id, date, visit_count, daily_total_amount, 
sum(visit_count) over (partition by id order by date range between interval '6' day preceding and current row) as rolling_visit_sum 
from (

select id, date, count(*) as visit_count, sum(total_amount) as daily_total_amount 
from (

select id, date, time, store, sum(currency_amount) as total_amount 
from table 
group by id, date, time, store 
having sum(currency_amount) >= 1000 

) 
group by id, date 
order by id, date 

) 
group by id, date, visit_count, daily_total_amount 

) 
where rolling_visit_sum = 2; 

我想重新運行查詢,看看結果如何隨着我改變參數(使用[$ 1000,$ 2000,$ 3000,$ 4000,$ 5000,$ 6000,$ 7000,$ 8000,$ 9000]作爲最小sum( currency_amount)閾值和[1,2,3,4,5,6]作爲必要條件rolling_visit_sum)。我想這可以通過某種循環來實現自動化,但是當我嘗試搜索如何自己做這件事時,我對此很陌生並且感到困惑。

理想我想結束與一個輸出表類似於下面的(與X的填充查詢結果:

sum(currency_amount) | rolling_visit_sum | count(*) 
    1000     1     x 
    1000     2     x 
    1000     3     x 
    1000     4     x 
    1000     5     x 
    1000     6     x 
    2000     1     x 
    2000     2     x 
    2000     3     x 
    2000     4     x 

.......

sum(currency_amount) | rolling_visit_sum | count(*) 
    9000     3     x 
    9000     4     x 
    9000     5     x 
    9000     6     x 

只要我能夠區分每個參數組合的結果,結果的實際格式並不重要,任何指導都將非常感謝!

回答

0

這裏是一個如何在T-SQL中實現它的例子,它可以幫助你(即使我假設你使用的是oracle,但oracle的確和遊標具有相似的邏輯)。你也可以使用一個正常的oracle循環語句(在google中有很多例子可用)。

-- declare variables 

declare @ParamterCurrencyAmount numeric(26, 2), 
     @ParameterRollingVisitSum int 


-- declare table variable 

declare @CurrencyAmounts table 
(
    CurrencyAmount numeric(26, 2) 
) 

-- declare table variable 

declare @RollingVisitSums table 
(
    RollingVisitSum int 
) 


-- insert sample data 

insert into @CurrencyAmounts 
(
    CurrencyAmount 
) 
select 1000 union all 
select 2000 union all 
select 3000 union all 
select 4000 union all 
select 5000 union all 
select 6000 union all 
select 8000 union all 
select 9000 

insert into @RollingVisitSums 
(
    RollingVisitSum 
) 
select 1 union all 
select 2 union all 
select 3 union all 
select 4 union all 
select 5 union all 
select 6 



-- join the data together for a cursor and loop through the cursor 

declare ParameterCursor cursor local static read_only forward_only for 
select CurrencyAmounts.CurrencyAmount, 
RollingVisitSums.RollingVisitSum 
from @CurrencyAmounts CurrencyAmounts, 
@RollingVisitSums RollingVisitSums 

open ParameterCursor 
fetch next from ParameterCursor 

into @ParamterCurrencyAmount, @ParameterRollingVisitSum 

while @@FETCH_STATUS = 0 
begin 


    print @ParamterCurrencyAmount 
    print @ParameterRollingVisitSum 


    -- do your code here whatever you wanna do with your parameters 



    fetch next from ParameterCursor 
    into @ParamterCurrencyAmount, @ParameterRollingVisitSum 

end 


close ParameterCursor; 
deallocate ParameterCursor; 
相關問題