There are 2 tables:
reference:
id | score | value | type_id
1 | 0 | 10 | 1
2 | 1 | 20 | 1
3 | 2 | 30 | 1
.. | .. | .. | ..
result:
id | score | type_id
1 | 2 | 1
2 | 7 | 2
3 | 0 | 3
I want to get value
from refernce
table for each type_id
depending on the score
in result
table.
The query:
SELECT ref.score, ref.value, ref.type_id
FROM `refernce` ref
JOIN `result` res
ON ref.type_id = res.type_id
WHERE res.score >= ref.score
GROUP BY ref.type_id
ORDER BY ref.id DESC;
The output in this case should be:
score | value | type_id
0 | 8 | 3
3 | 25 | 2
2 | 30 | 1
But this is the actual output:
score | value | type_id
0 | 8 | 3
0 | 5 | 2
0 | 10 | 1
So if the score
in result
table exists in refernce
the value
for this score and if the score
in result
table is greater than in the refernce
table the value
of the greater score
which is 3 should be returned.
Here is a fiddle: http://sqlfiddle.com/#!9/ecf1e3/1
2
Answers
use MAX 🙂 to get the highest value … and then join again based on those two values …
In case you are using some more sophisticated DB (Postgre, Oracle, ..)
You can use window functions to partition and order the rows .. and then only filter in the subsequent select the ones you need
Example (not tested)
A solution that used only one subquery from joining the
reference
andresult
tables, where thescore
andvalue
columns are converted to fixed-length hexadecimal string representations, combined and themax
aggregation function is applied to them, after which the hexadecimal strings are converted back to integers.Result:
SQL Fiddle.