2010-05-06 62 views
3

我有3個表來加入以獲取table1.code,table1.series,table2.entry_date,table3.title1 並且我試圖獲取最近的非null table1.title1按table1.code和table1.series分組。在select語句中獲取每個組的最近條目

select table1.code, table1.series, max(table2.entry_date), table3.Title1 
       from table3 INNER JOIN table2 ON table3.ID = table2.ID 
       INNER JOIN table1 ON table2.source_code = table1.code 
       where table3.Title1 is not NULL 
       group by table1.code, table1.series, table3.Title1 

似乎給了我一個非null的title1而不是最近的所有條目。我應該如何構建查詢來挑選最新版本的Title1代碼&系列?

+0

你能否提供一些樣本數據? – DForck42 2010-05-07 15:33:11

回答

2

試試這個:

select table1.code, table1.series, max(table2.entry_date), max(table3.Title1) as Title1 
from table3 
INNER JOIN table2 ON table3.ID = table2.ID 
INNER JOIN table1 ON table2.source_code = table1.code 
where table3.Title1 is not NULL 
And Table2.entry_Date = (Select Max(sq.entry_Date) 
         From sq.table2 
         Where sq.id = table2.ID) 
group by table1.code, table1.series 
+0

這給出了最近的日期,但沒有添加相應的最新標題。 – TheObserver 2010-05-07 00:43:31

+0

也許你需要改變表格的順序;所以從table1中選擇,然後加入到table2和table3中。你能發佈一些DDL和樣本數據嗎? – codingbadger 2010-05-07 06:55:45

0

也許這樣的事情只能加入在最近的表2項?

SELECT 
    table1.code, 
    table1.series, 
    table2.entry_date, 
    table3.Title1 
FROM 
    table1 
INNER JOIN 
    table2 
ON 
    table2.source_code = table1.code 
AND 
    table2.entry_date = 
(
    SELECT 
     MAX(maxtable2.entry_date) 
    FROM  
     table2 maxtable2 
    WHERE 
     maxtable2.source_code = table2.source_code 
) 
INNER JOIN 
    table3 
ON 
    table3.ID = table2.ID 
0
;with tlb as 
(
    select table1.code, table1.series, table2.entry_date, table3.Title1, 
    row_number() over(code, series, entry_date order by code, series, entry_date desc) as rn 
    from table3 INNER JOIN table2 ON table3.ID = table2.ID 
    INNER JOIN table1 ON table2.source_code = table1.code 
    where table3.Title1 is not NULL 
) 
select * from tlb where rn = 1 

這可以根據您的指標是非常快的。