Skip to content
Advertisement

pgsql: filter column to get latest value

I have below query to pivot, how to get status value filtered on latest updated_on row for each obj_key

select obj_key, max(updated_on) as updated_on, max(att.status) as status,
  COALESCE(max(array_to_string(v_date,'||'::text)) filter (where att.type_key=1),(select default_value from types where type_key=1))  as "DOB",
  COALESCE(max(array_to_string(v_text,'||'::text)) filter (where att.type_key=2),(select default_value from types where type_key=2)) as "First Name",
  COALESCE(max(array_to_string(v_text,'||'::text)) filter (where att.type_key=3),(select default_value from types where type_key=3))as "Last Name",
  COALESCE(max(array_to_string(v_number,'||'::text)) filter (where att.type_key=4),(select default_value from types where type_key=4)) as "Contact"
  from attributes att right join types ty on att.type_key=ty.type_key
  group by obj_key 

Table/data is here dbfiddle

i was trying by first_value(status) OVER( ORDER BY updated_on) AS status but no luck

Can we get status as per max(updated_on) for each obj_key ?

Advertisement

Answer

Try this version, the first_value(status) is changed to last_value(status) and the OVER W has been moved to the aggregate, so inside of the COALESCE statements.

select DISTINCT ON (obj_key) 
   obj_key, updated_on, 
   last_value(status) OVER w AS created_by,
   COALESCE(max(array_to_string(v_date,'||'::text)) filter (where 
   att.type_key=1) OVER w ,(select default_value from types where 
   type_key=1))  as "DOB",
   COALESCE(max(array_to_string(v_text,'||'::text)) filter (where 
   att.type_key=2) OVER w ,(select default_value from types where 
   type_key=2))  as "First Name",
   COALESCE(max(array_to_string(v_text,'||'::text)) filter (where 
   att.type_key=3) OVER w ,(select default_value from types where 
   type_key=3)) as "Last Name",
   COALESCE(max(array_to_string(v_number,'||'::text)) filter (where 
   att.type_key=4) OVER w ,(select default_value from types where 
   type_key=4)) as "Contact"
   from attributes att right join types ty on att.type_key=ty.type_key
   WINDOW w AS (PARTITION BY obj_key ORDER BY updated_on)
   ORDER  BY obj_key, updated_on DESC NULLS LAST;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement