我遇到的问题是我在针对数据库运行脚本以获取需要转换为DateTimes的多个VARCHAR之间的平均差异,然后取所有结果之间的平均值。
我的代码是:
SELECT YEAR(b.DateAcknow),AVG(datediff(dd,convert(datetime,b.DateAssign),
convert(datetime,b.DateResolv))) as DayAverage,
AVG(datediff(hh,convert(datetime,b.TimeAcknow),
convert(datetime,b.TimeResolv))) as HourAverage
FROM table AS b
WHERE (x = y)
AND YEAR(DateResolv) >= 2006
AND YEAR(DateResolv) < 2016
AND b.resolution <>''
GROUP BY YEAR(b.DateAcknow)
ORDER BY YEAR(b.DateAcknow)`
我得到的结果似乎没有意义,更不用说包括1900超出我的where子句的参数
这是:
NULL 42 NULL
1900 0 12
2006 7 -5
2007 6 1
2008 7 1
2009 4 1
2010 2 0
2011 2 0
2012 2 0
2013 2 0
2014 2 0
2015 2 0
我转换VARCHAR
错了吗?
我怀疑2010 - 2015年数以千计的参赛作品的平均成绩是2天0小时,所以要么我做错了,要么数据不好。
答案 0 :(得分:1)
您正在按DateResolv进行过滤,并按DateAcknow进行分组。
按相同的字段过滤和分组,NULL和范围之外的值应该消失。
答案 1 :(得分:1)
您可能想要带走聚合部分并运行:
SELECT YEAR(b.DateAcknow)
, convert(datetime,b.DateAssign) AS DateAssignDateTime
, convert(datetime,b.DateResolv) AS DateResolveDateTime
, datediff(dd,convert(datetime,b.DateAssign), convert(datetime,b.DateResolv)) AS AssignResolveDayDiff
, convert(datetime,b.TimeAcknow) AS TimeAcknowDateTime
, convert(datetime,b.TimeResolv) AS TimeResolveDateTime
, datediff(hh,convert(datetime,b.TimeAcknow), convert(datetime,b.TimeResolv)) AS AcknowResolveHourDiff
FROM table AS b
WHERE (x = y)
AND YEAR(DateAcknow) >= 2006
AND YEAR(DateAcknow) < 2016
AND b.resolution <>''
ORDER BY YEAR(b.DateAcknow)
确保您的所有转化都有意义。然后,您将更好地了解它实际上是什么。
之后,如果全部结账,那么您的查询应该可以正常工作(不过,请检查mxix&#39;是否改变
...
AND YEAR(DateResolv) >= 2006
AND YEAR(DateResolv) < 2016
...
到
...
AND YEAR(b.DateAcknow) >= 2006
AND YEAR(b.DateAcknow) < 2016
...
对你有意义。
如果您正在寻求提高输出的精确度,请尝试转换您的日期,如下所示:
旧:AVG(datediff(dd,convert(datetime,b.DateAssign), convert(datetime,b.DateResolv)))
新:AVG(Convert(Decimal(10, 5), datediff(dd,convert(datetime,b.DateAssign), convert(datetime,b.DateResolv))))
您的旧查询是平均天数,四舍五入到最接近的整数值,为您提供类似&#39; 2&#39;的值。这个新的调整将给你答案,如&#34; 1.51235&#34;而不是。
由于存在差异的100k记录(加号和减号),如果它们遵循正常或均匀分布,则平均值很可能接近于零。还试试:
AVG(Convert(Decimal(10, 5), ABS(datediff(dd,convert(datetime,b.DateAssign), convert(datetime,b.DateResolv)))))
如果你想要绝对差异。如果您的旧数据具有值&#34; 5,-3,4,-1,3&#34;,则旧方法将产生2的平均值,但如果您有&#34; ABS&#34;处理它们的函数,它会将值更改为&#34; 5,3,4,1,3和#34;并将在++方向上移动你得到的平均值(在这里,它变为&#34; 3&#34;或者&#34; 3.2&#34;,如果你也进行了十进制转换)。
答案 2 :(得分:0)
我的意图是每年显示平均回答是什么 时间是天和小时。 - obizues
假设:
如果您需要有关varchar date格式和convert函数的帮助,请参阅: http://msdn.microsoft.com/en-us/library/ms187928.aspx
以下方法应该有助于实现您的目的:
SELECT YEAR(b.DateAcknow)
, AVG(DateDiff(Day, Convert(datetime, b.DateAcknow) + convert(datetime, b.TimeAcknow), Convert(datetime, b.DateResolv) + Convert(datetime, b.TimeResolve))) AS AvgDaysDifference
, AVG(DateDiff(Hour, Convert(datetime, b.DateAcknow) + convert(datetime, b.TimeAcknow), Convert(datetime, b.DateResolv) + Convert(datetime, b.TimeResolve))) AS AvgHoursDifference
FROM table AS b
WHERE (x = y) AND YEAR(DateAcknow) >= 2006 AND YEAR(DateAcknow) < 2016
AND b.resolution <>''
GROUP BY YEAR(b.DateAcknow)
如果您对数据和意图的假设是正确的,那么应该这样做。当它不清楚时很难提供帮助。