Burbas
Burbas

Reputation: 803

Using MAX function within a join

I'm having some trouble with getting this SQL right. There is a one-to-many relationship between the iPad- and statlog tables and I want to select the statlog with highest value.

My first solution was to include a nested SELECT which grabbed the MAX-value for me, but since this took a lot of time I'm forced to rewrite it.

SELECT 
  ipad.udid, 
  ipad.state, 
  statelog.new_state 
FROM 
  ipad 
LEFT OUTER JOIN 
  statelog 
ON 
  ipad.udid = statelog.udid 
WHERE 
  ipad.airid=250033
  AND 
  statelog.new_state = MAX(statelog.new_state) 

This SQL does not work, but it shows my intention.

Upvotes: 2

Views: 6308

Answers (1)

SWeko
SWeko

Reputation: 30902

Something like this will work

SELECT ipad.udid, ipad.state, max(statelog.new_state)
FROM ipad  
  LEFT OUTER JOIN statelog ON ipad.udid = statelog.udid  
WHERE ipad.airid=250033
GROUP BY ipad.udid, ipad.state

MAX and other aggregate functions in SQL (min, sum, count, average, etc..) work on groups of values. The join generates one row for every statelog for every ipad, so if you have 10 ipads, with 8 statelogs each, you'll get 80 rows. The Group by groups those 80 rows for every ipad (their ipad.udid and ipad.state columns are the same), and in the scope of that group uses max(statelog.new_state) to extract the maximum state.

Upvotes: 6

Related Questions