sql - pgsql: Select different unique columns with newest timestamp -


i have psql table columns: write_date, tagwaarde, tagnaam, tagkwaliteit, schrijven. need retrieve newest unique value each column "schrijven" true.

hard explain here example: enter image description here

in case want output:

[('bakkerij.device1.db100int0', 777), ('bakkerij.device1.db100int8', 0)] 

because:

bakkerij.device1.db100int0 = 777 , bakkerij.device1.db100int0 = 666

=> 777 has newest timestamp

i have tried select tagnaam, tagwaarde inlezen schrijven = true order write_date desc limit 1

this gives

[('bakkerij.device1.db100int8', 0)] 

as output.

i have tried things distinct couldn't work.

what right way solve this? in advance!

this can done postgres' distinct on () operator:

select distinct on (tagnaam) tagnaam, tagwaarde  inlezen  schrijven = true  order tagnaam, write_date desc 

if prefer standard ansi sql solution, can done using window function:

select tagnaam, tagwaarde (     select tagnaam, tagwaarde,             row_number() on (partition tagnaam order write_date desc) rn     inlezen      schrijven = true  ) t rn = 1 order tagnaam; 

the distinct on faster solution window function.


Comments