I have two tables and I would like to get MAX(date) from one-to-many table. If there is no value, it should be NULL. Only way I know how to do it by making sub queries but if there is ~20 different types then 20 sub queries does not sound efficient enough. Is there any better way to do it?
Table A: UserId | Name 1 | John 2 | Jane Table B: UserId | Type | Date 1 | A | 2015-01-01 1 | A | 2015-12-31 1 | B | 2015-01-01 1 | B | 2015-12-31 2 | B | 2015-06-06 1 | C | 2015-01-01 2 | C | 2015-09-09 Result: UserId | Type A date | Type B date | Type C date 1 | 2015-12-31 | 2015-12-31 | NULL 2 | NULL | 2015-06-06 | 2015-09-09
Current solution:
SELECT UserId,
(SELECT MAX(Date) FROM B WHERE Type = 'A' AND B.UserId= A.UserId),
(SELECT MAX(Date) FROM B WHERE Type = 'B' AND B.UserId= A.UserId),
(SELECT MAX(Date) FROM B WHERE Type = 'C' AND B.UserId= A.UserId
AND Date > (SELECT MAX(Date) FROM B WHERE Type = 'B' AND B.UserId = A.UserId))
FROM A
Thank you for all quick answers! They work perfectly. I modified my question little bit since I noticed that I need to add some conditions on some types. For example. Type C should be only presented if it's bigger than type B.