Consider following query
SELECT DISTINCT FunctionNbr,FunctionDesc, MAX(date_altered)
FROM Persontable
WHERE FunctionNbr IN ('00000001','00000002','00000003')
AND LEN(RTRIM(FunctionDesc)) > 0
GROUP BY FunctionNbr,FunctionDesc
the persontable contains all the employees with their respective function. the date_altered may vary depending on changes made on SAP.
My expected output would be that i get a record for every employee with one of those functionNbr and with the same date_altered.
example of expected output:
FunctionNbr | FunctionDesc | date_altered
--------------------------------------------
00000001 | Function A | 2014-01-01 (=row from employee 001 with functionNbr = 0000001 and date_altered = 2013-12-20)
00000001 | Function A | 2014-01-01 (=row from employee 002 with functionNbr = 0000001 and date_altered = 2013-12-24)
00000001 | Function A | 2014-01-01 (=row from employee 003 with functionNbr = 0000001 and date_altered = 2014-01-01)
00000002 | Function B | 2013-12-13 (=row from employee 004 with functionNbr = 0000002 and date_altered = 2013-12-13)
00000002 | Function B | 2013-12-13 (=row from employee 005 with functionNbr = 0000002 and date_altered = 2013-12-11)
yet my output looks as follows:
FunctionNbr | FunctionDesc | date_altered
--------------------------------------------
00000001 | Function A | 2013-12-20 (=row from employee 001 with functionNbr = 0000001 and date_altered = 2013-12-20)
00000001 | Function A | 2013-12-24 (=row from employee 002 with functionNbr = 0000001 and date_altered = 2013-12-24)
00000001 | Function A | 2014-01-01 (=row from employee 003 with functionNbr = 0000001 and date_altered = 2014-01-01)
00000002 | Function B | 2013-12-13 (=row from employee 004 with functionNbr = 0000002 and date_altered = 2013-12-13)
00000002 | Function B | 2013-12-11 (=row from employee 005 with functionNbr = 0000002 and date_altered = 2013-12-11)
Question: In this case, Why doensn't the MAX() function always take the last date_altered
Note: For every employee there is only 1 row
FunctionNbrwith value00000001anyway? It's not in yourINclause... Please provide consistent information in your question!DISTINCTandGROUP BYin the sameSELECTclause. They do the same/similar things and you're giving them conflicting parameters. I am pretty sure that it's undefined what happens to SQL in this case.SELECT DISTINCT FunctionNbr,FunctionDesc, MAX(CAST(date_altered AS DATE))it is possible that the dates are stored as text