2014-01-27 14 views
0

考虑下面的查询的SQL Server 2008 - 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包含了所有与它们各自的功能雇员。 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) 

问题:在这种情况下,为什么doensn't的MAX()函数始终以上次date_altered

注:对于每个员工只有1行

+1

的正确建议如何可以将函数返回'FunctionNbr'与值'00000001'呢?这不在你的“IN”条款中......请在你的问题中提供一致的信息! –

+0

您不应该在同一个'SELECT'子句中使用'DISTINCT'和'GROUP BY'。他们做相同/相似的事情,你给他们冲突的参数。我很确定这是不确定的,在这种情况下,SQL会发生什么。 – RBarryYoung

+0

@Dittmar我的错误。试图用简单的例子来做,但忘了改变查询。直接这样做@ @ RBarryYoung删除了独特的测试你的陈述,但输出仍然保持不变。 – User999999

回答

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 

我已经删除了DISTINCT通过RBarryYoung