0

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.

Agh
  • 23
  • 4
  • @strawberry... not a full duplicate... different issue here – RoMEoMusTDiE Jun 08 '17 at 22:37
  • @mastashufu not if your answer is anything to go by – Strawberry Jun 08 '17 at 22:45
  • @Strawberry simple english please.. as far as i know it should fix the issue – RoMEoMusTDiE Jun 08 '17 at 22:46
  • I'm sorry but I don't see this is duplicated. PersonID and ValueID are unique. I cannot GROUP BY any of them. I haven't been able to find a solution yet. Thanks for your help – Agh Jun 09 '17 at 02:27
  • Looks like an exact duplicate to me `SELECT a.*,x.valueid,x.column1 FROM tablea a JOIN tableb x.* ON x.personid = a.personid JOIN ( SELECT personid , MAX(valueid) valueid FROM tableb GROUP BY personid ) y ON y.personid = x.personid AND y.valueid = x.valueid` – Strawberry Jun 09 '17 at 05:42

2 Answers2

0

Try This.. presumably the valueid is unique/ identity seeded

SELECT ps.*, 
(SELECT Column1 FROM b 
where b.valueId =(SELECT MAX(ValueID) FROM b as x
  WHERE x.PersonID = ps.PersonID)
) AS Column1  
FROM a ps 
RoMEoMusTDiE
  • 4,739
  • 1
  • 17
  • 26
-1

Try this:

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