这是我目前的表。
员工将有多个订单日期和发货日期。我想得到的是每个员工的差异总和的平均值。
一直在努力实现这一目标。
这是我到目前为止所做的。
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
答案 0 :(得分: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
答案 1 :(得分: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