Getting the most recent entry for each group in a select statement

I have 3 tables to join to get table1.code, table1.series, table2.entry_date, table3.title1 and I'm trying to get the most recent null table table3.title1, grouped by table1.code and table1.series.

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
It seems that

gives me all entries with null header1 instead of the very last one. How should I structure the query to simply select the latest version of Title1 for each code and series?

+3
source share
3 answers

Try the following:

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
+2
source

Maybe something like this to only join the last of table2 entries?

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

.

0

Source: https://habr.com/ru/post/1744293/


All Articles