1pa
1pa

Reputation: 735

How to select distinct on with different order by Postgresql

Hello i want to query a table and make a select distinct on but with different ordey by and i want this with desc. How can i do this?

CREATE TABLE test_dupl2(id SERIAL, letter_one TEXT, number_int INT, primary key (id));

INSERT INTO test_dupl2(letter_one,number_int) VALUES ('A',1), ('A',2), ('B',1), ('A', 9), ('B', 4);

My query

select letter_one, number_int from
    (SELECT DISTINCT ON (letter_one) letter_one, number_int FROM test_dupl2) as foo
order by foo.number_int desc;

The wrong output:

('A', 1), ('B', 1)

The output i want:

('A', 9), ('B', 4)

Postgresql9.4

Upvotes: 1

Views: 1343

Answers (1)

klin
klin

Reputation: 121604

select distinct on (letter_one) letter_one, number_int 
from test_dupl2
order by 1, 2 desc;

 letter_one | number_int 
------------+------------
 A          |          9
 B          |          4
(2 rows)

Upvotes: 1

Related Questions