I must get max date values from one column from multiple rows in 2 columns based on IdType in one rows for IDUser.
I simplify my tables like this :
TableDoc
IDUser IdCourse
John C
Jeff E
Michael F
Tom A
John E
Jeff C
Michael A
Tom E
TableCourse
IdCourse IdType DateCourse
A 2 2020-07-31 00:00:00
C 2 2019/06/06 00:00:00
C 1 2021/04/14 00:00:00
E 2 2021/04/29 00:00:00
E 2 2020/06/09 00:00:00
F 1 2020/06/25 00:00:00
F 2 2021/04/09 00:00:00
F 2 2020/06/01 00:00:00
I must get this:
IDUser DateInsert DateUpdate
Jeff 2021-04-14 00:00 2021-04-29 00:00
John 2021-04-14 00:00 2021-04-29 00:00
Michael 2020-06-25 00:00 2021-04-09 00:00
Tom null 2021-04-29 00:00
This is my query:
SELECT d.IDUser, c.IdType,
DateInsert = MAX(CASE WHEN c.IdType = 1 THEN DateCourse END),
DateUpdate = MAX(CASE WHEN c.IdType = 2 THEN DateCourse END)
FROM dbo.TableDoc d
inner join TableCourse c
on d.IdCourse = c.IdCourse
GROUP BY IDUser;
In [Sql Fiddle][1] is ok, but in Sql Server Management (with my real tables) I have this error:
Column 'TableCourse.IdType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.```
What could be the problem?
[1]: http://sqlfiddle.com/#!18/9c982/3