2010-05-06 60 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 

这可以根据您的指标是非常快的。