0

I have a query which returns results in the 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 basically for each user in the database, it lists 3 rows, each corresponding to TypeA, TypeB, TypeC. Now I need to return the user ID which corresponds to the maximum value for each type. So for example, from the data above we would obtain:

TypeA User2
TypeB User2
TypeC User1

I'm not sure how to proceed with this in SQL.

1
  • Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Nov 8, 2016 at 12:34

2 Answers 2

1

A typical way of doing this uses row_number():

with t as (
      <your query here>
     )
select t.*
from (select t.*,
             row_number() over (partition by typecol order by col3 desc) as seqnum
      from t
     ) t
where seqnum = 1;

Postgres offers another solution which is typically more efficient:

select distinct on (typecol) q.*
from (<your query here>) q
order by typecol, col3 desc;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

 SELECT X.col2,X.col1 FROM
    (SELECT col1,col2,col3,row_number() over (partition by col2 order by col3 desc) as seq,
    FROM table1)X
    WHERE X.seq = 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.