Skip to content
Advertisement

Get data from same row with MAX()?

[MariaDB 10.4, PHP8.0] How can I rewrite this so it works so it get weight_date from the row with MAX(total_weight) and list it AS highest_weight_date? I have read that we can’t use MAX() among with WHERE? I have tested to rewrite several examples, but I give up and embarrassed show my latest try:

weight_date HAVING total_weight=MAX(total_weight) AS highest_weight_date

I try to add it to this but I get error. https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=9c057570bd60cdf20a7148189a77fdc4

    SELECT *
           , LEAD(total_weight, 1) OVER(
               ORDER BY weight_date DESC
           ) AS prev_total_weight
           , LEAD(weight_date, 1) OVER(
               ORDER BY weight_date DESC
           ) AS prev_total_weight_date
    
           , MIN(total_weight) OVER() AS lowest_weight
           , MAX(total_weight) OVER() AS highest_weight
 
           , FROM_UNIXTIME(weight_date, '%u') AS weight_week
           , ROW_NUMBER() OVER(
              ORDER BY weight_date DESC
           ) AS RowNum      

    FROM   (
              SELECT *, weight_start_week + weight_end_week AS total_weight
              FROM   YourTable
           ) t
    ORDER BY RowNum

Thanks

Advertisement

Answer

To get the highest_weight_date (the weight_date from the row that has the highest total_weight), you just want to add to your select:

FIRST_VALUE(weight_date) OVER (ORDER BY total_weight DESC) AS highest_weight_date

though I would recommend doing ORDER BY total_weight DESC, weight_date or ORDER BY total_weight DESC, weight_date DESC so you deterministically get either the first or last date with that weight, not an arbitrary one, when the weight occurs on more than one date.

fiddle

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement