Home > Software engineering >  Get max record for each group of records, link multiple tables
Get max record for each group of records, link multiple tables

Time:10-11

I seek to find the maximum timestamp (ob.create_ts) for each group of marketid's (ob.marketid), joining tables obe (ob.orderbookid = obe.orderbookid) and market (ob.marketid = m.marketid). Although there are a number of solutions posted like this for a single table, when I join multiple tables, I get redundant results. Sample table and desired results below:

table: ob

orderbookid marketid create_ts
1 1 1664635255298
2 1 1664635255299
3 1 1664635255300
4 2 1664635255301
5 2 1664635255302
6 2 1664635255303

table: obe

orderbookentryid orderbookid entryname
1 1 'entry-1'
2 1 'entry-2'
3 1 'entry-3'
4 2 'entry-4'
5 2 'entry-5'
6 3 'entry-6'
7 3 'entry-7'
8 4 'entry-8'
9 5 'entry-9'
10 6 'entry-10'

table: m

marketid marketname
1 'market-1'
2 'market-2'

desired results

ob.orderbookid ob.marketid obe.orderbookentryid obe.entryname m.marketname
3 1 6 'entry-6' 'market-1'
3 1 7 'entry-7' 'market-1'
6 2 10 'entry-10' 'market-2'

CodePudding user response:

Use ROW_NUMBER() to get a properly filtered ob table. Then JOIN the other tables onto that!

WITH
    ob_filtered AS (
        SELECT
            orderbookid,
            marketid
        FROM
            (
            SELECT
                *,
                ROW_NUMBER() OVER (
                    PARTITION BY
                        marketid
                    ORDER BY
                        create_ts DESC
                ) AS create_ts_rownumber
            FROM
                ob
            ) ob_with_rownumber
        WHERE
            create_ts_rownumber = 1
        )

SELECT
    ob_filtered.orderbookid,
    ob_filtered.marketid,
    obe.orderbookentryid,
    obe.entryname,
    m.marketname
FROM
    ob_filtered
    JOIN m 
        ON m.marketid = ob_filtered.marketid
    JOIN obe 
        ON ob_filtered.orderbookid = obe.orderbookid
;
  • Related