postgresql - Maximum values from SELECT SQL Query -


i have query returns results in following format:

user1 typea 3 user1 typeb 29 user1 typec 100 user2 typea 221 user2 typeb 31 user2 typec 32 user3 typea 21 user3  typeb 1 user3 typec 10 .... 

so each user in database, lists 3 rows, each corresponding typea, typeb, typec. need return user id corresponds maximum value each type. example, data above obtain:

typea user2 typeb user2 typec user1 

i'm not sure how proceed in sql.

a typical way of doing uses row_number():

with t (       <your query here>      ) select t.* (select t.*,              row_number() on (partition typecol order col3 desc) seqnum       t      ) t seqnum = 1; 

postgres offers solution typically more efficient:

select distinct on (typecol) q.* (<your query here>) q order typecol, col3 desc; 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -