使用CASE然后使用CAST,然后使用CAST值执行平均值

时间:2016-10-25 10:58:42

标签: sql

我在下面有以下SQL,它返回每个构建的构建时间,但现在我想给我一个构建的平均构建时间。 BuildStartTime& BuildFinishTime是DateTime字段。

SELECT
Build_Quality.TeamProject,
DATEPART(year, BuildStartTime) AS Year,
DATENAME(month, BuildStartTime) AS Month,
--Get the Build Time
 CASE When buildname LIKE 'CI-%' then CAST(BuildFinishTime-BuildStartTime AS time(0)) END AS [CI Build Time],
 CASE When buildname LIKE '%AutoMerge%' then CAST(BuildFinishTime-BuildStartTime AS time(0)) END AS [Auto Merge Build Time],
 CASE When buildname NOT LIKE '%AutoMerge%' AND buildname NOT LIKE 'CI-%' then CAST(BuildFinishTime-BuildStartTime AS time(0)) END AS [Various Other Build Time]

FROM            
dbo.Build_Quality
GROUP BY
Build_Quality.TeamProject,
DATEPART(year, BuildStartTime),
DATENAME(month, BuildStartTime),
DATEPART(month, BuildStartTime),
BuildName,
BuildStartTime,
BuildFinishTime,
Build_Quality.BuildStatus

ORDER BY 
'Year',
DATEPART(month, BuildStartTime)

1 个答案:

答案 0 :(得分:0)

这取决于你平均想要的是什么?持续时间,持续时间或什么?但我认为这会给你一个想法:

WITH CTE AS (

        SELECT
            Build_Quality.TeamProject,
            DATEDIFF(HOUR, BuildStartTime, BuildFinishTime) AS DurationHours
        FROM            
            dbo.Build_Quality )

SELECT
        TeamProject
        , AVG(DurationHours)
FROM CTE
GROUP BY TeamProject