在这种情况下AVG()函数的正确用法是什么?

时间:2017-02-10 13:29:58

标签: sql sql-server

我写了一个查询,它给了我两个栏目 - 一栏是年(1997年到2017年),另一栏是几个月的员工任期。

Select  DATEPART(YEAR,Cast(USI.StartDate As Date)) AS Year,
        DATEDIFF(MONTH,Cast(USI.StartDate As Date),Cast(USI.EndDate As Date)) AS TenureInMonths
From    UserWorkHistory      UWH
Join    Users                U    On UWH.UserId = U.Id
Join    UserStoryItems       USI  On U.Id = USI.UserId
Join    UserWorkHistoryTypes UWHT On UWH.UserWorkHistoryTypeId = UWHT.Id
Where   
(
    U.Location Like '%Great Britain%'
 Or U.Location Like '%United Kingdom%'
 Or U.Location Like '%England%'
 Or U.Location Like '%UK%'
 Or U.Location Like '%U.K.%'
)
and    UWHT.Id = 1
And    USI.UserStoryItemTypeId = 1
And    Cast(USI.StartDate As Date) > DateAdd(Year, -20, GetDate())
And 
(
     (
        UWH.Role NOT LIKE '%Contract%'
     Or UWH.Role NOT LIKE '%Contractor%'
     Or UWH.Role NOT LIKE '%Freelance%'
     Or UWH.Role NOT LIKE '%Non-perm%'
     Or UWH.Role NOT LIKE '%non-permanent%'
    )
    Or 
    (
        USI.Title NOT LIKE '%Contract%'
     Or USI.Title NOT LIKE '%Contractor%'
     Or USI.Title NOT LIKE '%Freelance%'
     Or USI.Title NOT LIKE '%Non-perm%'
     Or USI.Title NOT LIKE '%non-permanent%'
     Or USI.Title NOT LIKE '%self-made%'
     Or USI.Title NOT LIKE '%(Contract)%'
    )
)
GROUP BY DATEPART(YEAR,Cast(USI.StartDate As Date)), Cast(USI.StartDate As Date), Cast(USI.EndDate As Date)      
ORDER BY DATEPART(YEAR,Cast(USI.StartDate As Date))

我想要做的是根据他们开始的年份找出每位员工的平均任期。例如,1997年而非2012年开始的员工的平均任期(以月为单位)。

我理解这一点需要使用AVG()函数,但是我不确定如何使用年份列中的所有年份来执行它,而不仅仅是添加

AVG(DATEDIFF(MONTH,Cast(USI.StartDate As Date),Cast(USI.EndDate As Date))) AS AVERAGE

它并不能给我每年的平均值。

我也明白GROUP BY子句在这里是必要的,但我不能仅仅是YEAR,因为Cast(USI.StartDate As Date),Cast(USI.EndDate As Date)需要包括在内。

1 个答案:

答案 0 :(得分:4)

在没有原始数据的情况下进行调试非常棘手,但您是否尝试过更换:

DATEDIFF(MONTH,Cast(USI.StartDate As Date),Cast(USI.EndDate As Date)) AS TenureInMonths

有类似的东西:

DATEDIFF(MONTH,Min(Cast(USI.StartDate As Date)),Max(Cast(USI.EndDate As Date))) AS TenureInMonths

允许您从GROUP BY中删除开始日期和结束日期?