How do I return rows with the max Value for each department and if two or more rows for the same Department have the same Value include those in the results?
For instance, I have the table below:
Name | Code | Date | Value |
---|---|---|---|
Finance | ABC12 | 2020-05-12 | 15 |
Finance | ABC12 | 2020-06-24 | 118 |
Marketing | BBG43 | 2020-05-12 | 12 |
Marketing | BBG43 | 2021-08-07 | 1 |
Tech | PKY76 | 2020-07-21 | 7 |
Tech | PKY76 | 2020-11-28 | 7 |
I want to return rows that have the maximum Value for each department. If a department has the same maximum Value on different days return all of those days.
For example, my desired output would be this:
Name | Code | Date | Value |
---|---|---|---|
Finance | ABC12 | 2020-06-24 | 118 |
Marketing | BBG43 | 2020-05-12 | 12 |
Tech | PKY76 | 2020-07-21 | 7 |
Tech | PKY76 | 2020-11-28 | 7 |
So far I have this code:
SELECT
Name
,Code
,MAX(Date)
,MAX(Value) AS Total
FROM Department
GROUP BY
Name
,Code
Obviously, the issue with this is that I don't want to get just the MAX date, but I don't know how to include the Date in the output without using it in the GROUP BY
. As a result, I'm only getting the results for each department with the latest date, in the case of multiple rows with the same department only one is included.