在select语句中获取每个组的最新条目

时间:2010-05-06 07:26:25

标签: sql sql-server tsql

我有3个表要加入以获取table1.code,table1.series,table2.entry_date,table3.title1 我正在尝试获取由table1.code和table1.series分组的最新非null table3.title1。

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&系列?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

也许像这样只能加入最新的table2条目?

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

答案 2 :(得分: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

这可以非常快,具体取决于您的索引。