Question
How can I add a specific value from a column when using a GROUP BY
statement and an aggregate function in my query?
Overview
This is a sample of my table:
id | year | quarter | wage | comp_id | comp_industry |
123 | 2012 | 1 | 1000 | 456 | abc |
123 | 2012 | 1 | 2000 | 789 | def |
123 | 2012 | 2 | 1500 | 789 | def |
456 | 2012 | 1 | 2000 | 321 | ghi |
456 | 2012 | 2 | 2000 | 321 | ghi |
To calculate the sum of each person's wage
value by quarter
and wage
, I ran the following query:
SELECT SUM(wage) AS sum_wage
FROM t1
GROUP BY id, year, quarter, sum_wage;
Results in
id | year | quarter | sum_wage |
123 | 2012 | 1 | 3000 |
123 | 2012 | 2 | 1500 |
456 | 2012 | 1 | 2000 |
456 | 2012 | 2 | 2000 |
Desired Output
I would like to update my query to include the comp_industry
column where the individual's wage
is highest for each quarter
and year
. I'm unsure where to start so that I only return the industry where folks made the most money for each quarter
and year
.
id | year | quarter | sum_wage | comp_industry
123 | 2012 | 1 | 3000 | def
123 | 2012 | 2 | 1500 | def
456 | 2012 | 1 | 2000 | ghi
456 | 2012 | 2 | 2000 | ghi
I've taken a look at Get value based on max of a different column grouped by another column and Fetch the row which has the Max value for a column but am unsure where to go from there.
Any help or advice would be greatly appreciated!