我目前正在尝试计算两个日期之间的差异,我已经成功了,但是我想要计算我创建的列别名的平均值。
目前我正在尝试使用的代码:
SELECT actualfinish, actualstart, internalpriority, DATEDIFF(mi, actualstart, actualfinish) AS [date difference], AVG(DATEDIFF(mi, actualstart, actualfinish) AS [AVG date diff]
FROM mytable
WHERE (internalpriority=1) AND (actualfinish IS NOT NULL) AND (actualstart IS NOT NULL)
ORDER BY [date difference];
有没有办法做到这一点?还是我在浪费时间?
非常感谢您的帮助。
答案 0 :(得分:1)
首先,您需要GROUP BY
为您的AVG
工作。至于立即使用别名,你不能。您可以使用CTE,派生表,也可以再次使用整个计算:
CTE方法
;WITH CTE AS
(
SELECT actualfinish,
actualstart,
internalpriority,
DATEDIFF(mi, actualstart, actualfinish) AS [date difference]
FROM mytable
WHERE (internalpriority=1) AND (actualfinish IS NOT NULL) AND (actualstart IS NOT NULL)
)
SELECT actualfinish,
actualstart,
internalpriority,
AVG([date difference]) OVER() [AVG date diff]
FROM CTE
ORDER BY [AVG date diff]
派生表:
SELECT actualfinish,
actualstart,
internalpriority,
AVG([date difference]) OVER() [AVG date diff]
FROM ( SELECT actualfinish,
actualstart,
internalpriority,
DATEDIFF(mi, actualstart, actualfinish) AS [date difference]
FROM mytable
WHERE (internalpriority=1) AND (actualfinish IS NOT NULL) AND (actualstart IS NOT NULL)) A
ORDER BY [AVG date diff]