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

SQL Server 2008-MAX()-函数生成无效/意外的输出,sql,sql-server,sql-server-2008-r2,max,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 persontable包含所有员工及其各自的功能。更改日期可能因SAP上的更

考虑以下查询

SELECT DISTINCT FunctionNbr,FunctionDesc, MAX(date_altered)
FROM Persontable
WHERE FunctionNbr IN ('00000001','00000002','00000003')
AND LEN(RTRIM(FunctionDesc)) > 0 
GROUP BY FunctionNbr,FunctionDesc
persontable包含所有员工及其各自的功能。更改日期可能因SAP上的更改而异

我的预期结果是,我会为每个具有这些功能之一的员工获得一份记录,记录的日期与更改的日期相同

预期产出示例:

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()函数不总是取最后一个日期


注意:每个员工只有一行

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

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
,您的函数如何返回
FunctionNbr
00000001
?它不在您的
in
子句中。。。请在您的问题中提供一致的信息!您不应该在同一
SELECT
子句中使用
DISTINCT
groupby
。他们做相同/相似的事情,你给他们的参数相互矛盾。我很确定,在这种情况下,SQL发生了什么还没有定义。@Dittmar是我的一个错误。尝试使用简单的示例来完成此操作,但忘记更改查询。将直接执行此操作。@RBarryYoung删除了distinct以测试您的语句,但输出仍然保持不变。请尝试:
选择distinct FunctionNbr、FunctionDesc、MAX(CAST(日期更改为日期))
日期可能存储为text@MarkD你说得对!日期存储为文本。每日更新显然增加了随机数量的尾随空格。例如“2013-12-20”。我真愚蠢,竟然忽略了最明显的事情。。。。你能把你的答案贴出来让我批准吗?