I have two tables:
table a:
PersonID | name | age | gender
-------- | ---- | --- | ------
20 | John | 45 | Male
30 | Ann | 50 | Female
table b:
ValueID | PersonID | Column1
------- | -------- | -------
1 | 20 | 654321
2 | 20 | 345653
3 | 30 | 756756
4 | 30 | 142857
I need to get all values from table 'a' and for each one a corresponding Column1 with a.PersonID = b.PersonID and with the MAX ValueID.
The expected result in this example would be the following:
PersonID | name | age | gender | Column1
-------- | ---- | --- | ------ -------
20 | John | 45 | Male | 345653
30 | Ann | 50 | Female | 142857
I tried this and doesn't work.
SELECT ps.*,
(SELECT Column1 FROM b ef
JOIN (SELECT MAX(ValueID) AS id FROM b
WHERE PersonID = ps.PersonID) max ON ef.PersonID = max.id ) AS Column1
FROM a ps
I guess ps.PersonID
in WHERE clause ef.PersonID = ps.PersonID
is not recognized.
I appreciate very much your help.