2

我目前正在尝试计算两个日期之间的差异,我已经成功了,但是我想计算我创建的列别名的平均值。

目前我正在尝试使用的代码:

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];

有没有办法做到这一点?还是我在浪费时间?

非常感谢您提前提供的帮助。

4

1 回答 1

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]
于 2013-06-25T13:32:00.880 回答