Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to get value of another column corresponding to a max value of a column based on group by

Tags:

sql

group-by

max

I have the following table:

ID     BLOWNUMBER    TIME            LADLE
---    ----------    ----------      -----
124      1           01/01/2012        2
124      1           02/02/2012        1
124      1           03/02/2012        0
124      2           04/01/2012        1
125      2           04/06/2012        1
125      2           01/03/2012        0    

I want to have the TIME for the maximum value of LADLE for a group of ID & BLOWNUMBER.

Output required:

124        1       01/01/2012
124        2       04/01/2012
125        2       04/06/2012
like image 656
user1823732 Avatar asked Nov 30 '25 02:11

user1823732


1 Answers

If you're using SQL Server (or another engine which supports CTE's and ROW_NUMBER), you can use this CTE (Common Table Expression) query:

;WITH CTE AS 
(
   SELECT 
      ID, BlowNumber, [Time],
      RN = ROW_NUMBER() OVER (PARTITION BY ID, BLOWNUMBER ORDER BY [Time] DESC)
   FROM Sample
)
SELECT *
FROM CTE
WHERE RN = 1

See this SQL Fiddle here for an online live demo.

This CTE "partitions" your data by (ID, BLOWNUMBER), and the ROW_NUMBER() function hands out numbers, starting at 1, for each of those "partitions", ordered by the [Time] columns (newest time value first).

Then, you just select from that CTE and use RN = 1 to get the most recent of each data partition.

like image 165
marc_s Avatar answered Dec 02 '25 17:12

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!