简体   繁体   中英

PostgreSQL query to get attributes based on join condition and max(date)

I have table structures below(screen). I want the result query as shown: from first table and second table on the basis of row_wid and max(req_createdOn) date field, get req_attr1 and req_attr_2 values. I'm using Greenplum Database (roughly PostgreSQL 8.2 compatible).

TIA.

在此处输入图片说明

2nd screen: As you see there are two row_wid in t1. for each row_wid from t1 in t2, we need to check the greatest req_createdOn date and get the attr1, attr2 for the max(req_createdOn). Any idea? Sorry for not putting this condition in the 1st screen. Thanks a lot. 在此处输入图片说明

There's special syntax in PostgreSQL for queries, distinct on clause:

select distinct on (t2.Row_wid)
    t1.sn, t1.Geo, t1.Region,
    t1.req_attr_1, t1.req_attr_2
from table1 as t1
    inner join table2 as t2 on t2.Row_wid = t1.Row_wid
order by t2.Row_wid, t2.req_created_on desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM