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.
Something like this will work
MAXand 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 bygroups those 80 rows for every ipad (their ipad.udid and ipad.state columns are the same), and in the scope of that group usesmax(statelog.new_state)to extract the maximum state.