SQL Server 2008 - MAX() - 函数产生无效/意外输出

时间:2014-01-27 14:56:31

标签: sql sql-server sql-server-2008-r2 max

考虑以下查询

SELECT DISTINCT FunctionNbr,FunctionDesc, MAX(date_altered)
FROM Persontable
WHERE FunctionNbr IN ('00000001','00000002','00000003')
AND LEN(RTRIM(FunctionDesc)) > 0 
GROUP BY FunctionNbr,FunctionDesc
个人表包含所有具有各自职能的员工。 date_altered可能会因SAP上的更改而有所不同。

我的预期输出是我获得每个具有其中一个functionNbr且具有相同date_altered的员工的记录。

预期产出的例子:

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)

但我的输出如下:

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)

问题:在这种情况下,为什么MAX()函数总是采用最后一个date_altered

注意:每位员工只有一行

1 个答案:

答案 0 :(得分:1)

表的日期很可能存储为文本。试试这个;

SELECT FunctionNbr,FunctionDesc, MAX(CAST(date_altered AS DATETIME)
FROM Persontable
WHERE FunctionNbr IN ('00000001','00000002','00000003')
AND LEN(RTRIM(FunctionDesc)) > 0 
GROUP BY FunctionNbr,FunctionDesc

我已根据RBarryYoung

的正确建议删除了DISTINCT