So few years later (2022), some correlated subqueries are support, but not this one:
using this data:
WITH transaction(id, terminalid) AS ( SELECT * FROM VALUES (1,10), (2,11), (3,12) ), terminal(id, terminalid, export_date) AS ( SELECT * FROM VALUES (100, 10, '2022-03-18'::date), (101, 10, '2022-03-19'::date), (102, 11, '2022-03-20'::date), (103, 11, '2022-03-21'::date), (104, 11, '2022-03-22'::date), (105, 12, '2022-03-23'::date) )
So compared to Marcin's we can now use a QUALIFY to select only one value per terminalid in a single step:
WITH last_terminal as ( SELECT id, terminalid FROM terminal QUALIFY row_number() over(PARTITION BY terminalid ORDER BY export_date desc) = 1 ) SELECT tr.ID, te.id FROM transaction AS tr JOIN last_terminal AS te ON te.TERMINALID = tr.TERMINALID ORDER BY 1;
giving:
and if you have multiple terminals per day, and terimal.id is incrementing number you could use:
QUALIFY row_number() over(PARTITION BY terminalid ORDER BY export_date desc, id desc) = 1
Now if your table is not that larger, you can do the JOIN then prune via the QUALIFY, and avoid the CTE, but on large tables this is much less performant, so I would only use this form when doing ad-hoc queries, where swapping forms if viable if performance problems occur.
SELECT tr.ID, te.id FROM transaction AS tr JOIN terminal AS te ON te.TERMINALID = tr.TERMINALID QUALIFY row_number() over(PARTITION BY tr.id ORDER BY te.export_date desc, te.id desc) = 1 ORDER BY 1;
ERROR: length for type varchar cannot exceed 10485760BTW: you dont have to specify a size for varchar().