Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get table with only rows of maximum value in a column partitioned by another column?

I’m trying to get the maximum value of calories consumed per day. I can’t figure out how to get a query result which I imagine to just be 1 row for each date, with a column containing the value for the total calories in each day.

Current MySQL query result here The value with red asterisk next to it is the value I want for each day.

with meals_in_day as

(
select *, 
row_number() over (partition by meal_date order by meal_name ) as meals_through_day,
sum(calories) over (partition by meal_date order by meal_name ) as incremental_calories
from calories_data
)

select *
from meals_in_day;

I got so far as summing the calories partitioned by meals each day, but I’m stuck from here. Hoping someone is able to help me reach my desired query result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!

>Solution :

To get the maximum value (which would be the total for the day), you can use a subquery that selects the maximum incremental_calories for each day.

WITH meals_in_day AS (
    SELECT
        meal_date,
        SUM(calories) OVER (PARTITION BY meal_date ORDER BY meal_name) AS incremental_calories
    FROM calories_data
)
SELECT
    meal_date,
    MAX(incremental_calories) AS total_calories
FROM meals_in_day
GROUP BY meal_date;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading