2013-12-09 38 views
0

我得到了一個帶有時間戳列(YYYY.MM.DD HH24:MI:SS)的源表以及每天都有聚合行的目標表(日期列:YYYY.MM.DD )。只彙總源表中的新行

我的問題是:如何將新數據從源代碼帶入目標並對其進行聚合?

我想:

select 
    a.Sales, 
    trunc(a.timestamp,'DD') as TIMESTAMP, 
    count(1) as COUNT, 
from 
tbl_Source a 
where trunc(a.timestamp,'DD') > nvl((select MAX(b.TIME_TO_DAY)from tbl_target b), to_date('01.01.1975 00:00:00','dd.mm.yyyy hh24:mi:ss')) 

group by a.sales, 
    trunc(a.Timestamp,'DD') 

與的問題是:當我有一排時間戳「2013年11月15日0時01分32秒」,並從目標最大的一天是月14日,它只會累計15日。我會使用> =而不是>某些行會加載兩次。

回答

0

這是否適合您的需要:

WHERE trunc(a.timestamp,'DD') > nvl((select MAX(b.TIME_TO_DAY) + 1 - 1/(24*60*60) from tbl_target b), to_date('01.01.1975 00:00:00','dd.mm.yyyy hh24:mi:ss')) 

即代替2013年11月15日0點〇〇分00秒比較2013年11月16日23時59分59秒

更新

這一個?

WHERE trunc(a.timestamp,'DD') BETWEEN nvl((select MAX(b.TIME_TO_DAY) from ...) AND nvl((select MAX(b.TIME_TO_DAY) + 1 - 1/(24*60*60) from ...) 
+0

感謝您的答案,但我不這麼認爲。可以說在目標中,我的最大日期是14日(因爲流程聚集了幾行,時間戳在0點之後關閉)和源15日00:01:32。現在我需要這兩次之間的所有行。 – user2428207

0

看起來你正在尋找一個MERGE語句:如果這一天是tbl_target已經存在然後更新計數否則插入記錄。

merge into tbl_target dest 
using 
(
    select sales, trunc(timestamp) as theday , count(*) as sales_count 
    from tbl_Source 
    where trunc(timestamp) >= (select nvl(max(time_to_day),to_date('01.01.1975','dd.mm.yyyy')) from tbl_target) 
    group by sales, trunc(timestamp) 
) src 
on (src.theday = dest.time_to_day) 
when matched then update set 
    dest.sales_count = src.sales_count 
when not matched then 
    insert (time_to_day, sales_count) 
    values (src.theday, src.sales_count) 
; 
0

據我瞭解你的問題:自上次重新載入目標表以來,你需要得到一切。

問題在這裏:你需要這個日期,但它在更新過程中被截斷。

如果我的猜測是正確的,除了將重新加載的日期作爲附加列存儲之外,您無法做任何事情,因爲無法從此處顯示的數據中取回它。

有關查詢:

  1. COUNT(*)和count(1)在性能相同的(證明了很多次,至少在10-11版) - 不要讓這個數(1) ,看起來真的很醜陋
  2. 不使用NVL,使用聚結而不是它 - 它的速度要快得多
  3. 我會寫你的查詢這樣的:

    with t as (select max(b.time_to_day) mx from tbl_target b) 
    select a.sales,trunc(a.timestamp,'dd') as timestamp,count(*) as count 
    from tbl_source a,t 
    where trunc(a.timestamp,'dd') > t.mx or t.mx is null 
    group by a.sales,trunc(a.timestamp,'dd')