2

I looking best or simplest way to SELECT type, user_with_max_value, SUM(value) GROUP BY type. Table look similar

type  | user | value
type1 | 1    | 100
type1 | 2    | 200
type2 | 1    | 50
type2 | 2    | 10

And result look:

type1 | 2 | 300
type2 | 1 | 60
1
  • 1
    Tag your question with the database you are using. Commented Apr 26, 2020 at 13:32

4 Answers 4

2

Use window functions:

select type, max(case when seqnum = 1 then user end), sum(value)
from (select t.*,
             row_number() over (partition by type order by value desc) as seqnum
      from t
     ) t
where seqnum = 1;

Some databases have functionality for an aggregation function that returns the first value. One method without a subquery using standard SQL is:

select distinct type,
       first_value(user) over (partition by type order by value desc) as user,
       sum(value) over (partition by type)
from t;
Sign up to request clarification or add additional context in comments.

2 Comments

. . . This doesn't have a total value.
@YogeshSharma . . . It does now. And your answer should not have been downvoted.
0

You can use window function :

select t.*
from (select t.type,
             row_number() over (partition by type order by value desc) as seq,
             sum(value) over (partition by type) as value
      from table t
     ) t
where seq = 1;

Comments

0

Try below query.

It will help you.

SELECT type, max(user), SUM(value) from table1 GROUP BY type

1 Comment

this wont work, the max user is not the right answer
0

use analytical functions

create table poo2
(
    thetype varchar(5),
    theuser int,
    thevalue int
)

insert into poo2 
select 'type1',1,100  union all
select 'type1',2,200  union all
select 'type2',1,50  union all
select 'type2',2,10  

select thetype,theuser,mysum
from
(
    select thetype  ,theuser  
    ,row_number() over (partition by thetype order by thevalue desc)    r   
    ,sum(thevalue) over (partition by thetype) mysum    from  poo2
) ilv
where r=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.