2016-08-02 20 views
0

我有一張過去4年的表格近900萬行 我需要列出近兩年來的近10萬個樣本。 這樣做雖然我可以選擇啓動2014年7月如何在Oracle中選擇表格中的過去2年的10行

select distinct tb1.field 
    from table1 tb1 
    join table2 tb2 
    on tb.field = tb2.field 
    where tb1.Date between to_date('1-July-2014','DD-MON-YYYY') and  to_date('8-Aug-2016','DD-MON-YYYY') 
    order by tb1.field 

感謝

+0

你用什麼樣的標準來選擇X每個月的行數? –

+0

我可以從頂部或底部選擇n行無關緊要的行,每隔一個月選擇100行,不要按特定順序隨機選擇。 – Uska

+0

您的查詢顯示您知道如何進行加入。 (也許)。行根據tb1中的日期字段隨機選擇 - 與tb2無關。樣本的選擇應在加入前在tb1中完成。那麼爲什麼這個連接是相關的?或者不是? – mathguy

回答

0

如果表TB1有一欄DT(我希望這不是所謂DATE,這是一個保留關鍵字,並使用從每個月X行它作爲列名很可能會導致錯誤),並且如果您需要從過去24個月的每個過程中獲得100個純粹隨機的行,則可以這樣做。然後,如果需要,您可以將結果加入其他表格。我假設tb1中的其他列(或者你需要加入的那些列)是col1,col2。

select col1, col2, dt 
from (
     select col1, col2, dt, 
       row_number() over (partition by trunc(dt, 'mm') 
            order by dbms_random.value() 
           ) as rn 
     from tb1 
     where dt between add_months(trunc(sysdate), -24) and sysdate 
    ) 
where rn <= 100 
; 
+0

謝謝Mathguy,這實際上給了我尋找的解決方案 – Uska

0

不知道您的SQL實例是如何與你所要求的英語...... 但你可以嘗試這樣的事:

with q1 as (select trunc(Date, 'month') mth, 
        min(Date) start_dt, 
        max(Date) end_dt 
      from table1 
      where date ... 
      group by trunc(Date, 'month')), 
    q2 as (select table1.*, 
        row_number() over (partition by trunc(Date,'month') 
             order by [some random column]) seq 
     where Date ...) 
select q2.* 
from q1 
join q2 
    on q2.Date between q1.start_dt and q1.end_dt 
    and q2.seq <= [x] 
相關問題