1

这是我目前的桌子。

在此处输入图像描述

员工将有多个订单日期和发货日期。我想得到的是每个员工 Diff 总和的平均值。

一直在努力实现这一目标。

这是我到目前为止所做的。

USE Northwind 

SELECT 
    e.EmployeeID, 
    e.LastName, 
    o.OrderDate, 
    o.ShippedDate, 
    DATEDIFF(DAY, o.OrderDate, o.ShippedDate) as Diff 
FROM 
    Employees as e 
    JOIN Orders as o ON e.EmployeeID = o.EmployeeID
4

2 回答 2

4
SELECT 
    e.EmployeeID, 
    AVG(CAST(DATEDIFF(DAY, o.OrderDate, o.ShippedDate) as float)) as AvgDiff 
FROM 
    Employees as e 
    JOIN Orders as o ON e.EmployeeID = o.EmployeeID
Group By e.EmployeeID

如果您想要的不仅仅是EmployeeId结果集中的 ,请像这样重新加入:

select 
    e.EmployeeId
    e.LastName, 
    a.AvgDiff
From
    Employees as e 
Join     (SELECT 
              e.EmployeeID, 
              AVG(CAST(DATEDIFF(DAY, o.OrderDate, o.ShippedDate) as float)) as AvgDiff 
          FROM 
              Employees as e 
              JOIN Orders as o ON e.EmployeeID = o.EmployeeID
          Group By e.EmployeeID) a ON a.EmployeeId = e.EmployeeId
于 2012-11-14T07:13:56.230 回答
3
SELECT 
    e.EmployeeID, 
    e.LastName, 
    AVG(1.0 * DATEDIFF(DAY, o.OrderDate, o.ShippedDate)) as AVGDiff 
FROM 
    Employees as e 
    JOIN Orders as o ON e.EmployeeID = o.EmployeeID
Group by  e.EmployeeID, e.LastName
Order by  e.EmployeeID, e.LastName 
于 2012-11-14T07:13:33.197 回答