I have two tables:
table1 table2
column id column id column value
1 1 count_20
2 1 count_30
3 2 count_20
4 2 count_50
... 2 count_200
3 count_30
3 count_50
3 count_200
4 count_130
... ...
I want to build a query that will select every row from table1, column id and the MAX value from the corresponding column value from table2 and make a DESC short as int in value column.
So the output should be:
table1.id value
2 count_200
3 count_200
4 count_130
1 count_30
... ...
I have tried JOIN but then, for every value (count_%) in table2 I get the corresponding id from table1.
SELECT table1.id, table2.id, table2.value FROM table1
LEFT JOIN table2
ON table2.id=table1.id
WHERE table1.id<'100'
ORDER BY
CASE value
WHEN 'count_20' THEN '20'
END DESC,
CASE value
WHEN 'count_30' THEN '30'
END DESC,
CASE value
WHEN 'count_50' THEN '50'
END DESC,
CASE value
WHEN 'count_130' THEN '130'
END DESC,
CASE value
WHEN 'count_200' THEN '200'
END DESC;
Output:
table1.id table2.id value
2 2 count_200
3 3 count_200
4 4 count_130
2 2 count_50
3 3 count_50
1 1 count_30
3 3 count_30
1 1 count_20
2 2 count_20
... ...
Any help would be appreciated.
Give this a try:
This results in:
Fiddle here.