我需要帮助获得服务电话的平均交货时间。所以这就是我目前正在使用的。
***name Date_Assigned Date_Completed***
jon 8/17/2017 8/20/2017
jon 9/10/2017 9/11/2017
lucy 8/5/2017 8/5/2017
jon 8/19/2017 9/27/2017
我想找出:
1.) What the average service lead time for everyone collectively is.
2.) What the average service lead time per name is.
根据我的尝试,我必须制作日期格式并将其转换为日期时间。但似乎找不到合适的解决方案!谁能帮我吗???我使用的是SQL管理工作室或t-sql语法。谢谢!
答案 0 :(得分:1)
如果支持avg
窗口功能,您可以使用
select distinct name
,avg(datediff(day,date_assigned,date_completed)) over(partition by name) as avg_per_name
,avg(datediff(day,date_assigned,date_completed)) over() as avg_overall
from tbl
答案 1 :(得分:1)
一种方法是:
select name,
avg ( datediff(day, date_assigned, date_completed) )
from t
group by grouping sets ( (name), () );
这会将整体平均值放在一个单独的行中,NULL
的值为name
。
答案 2 :(得分:0)
-- Setup table
SET NOCOUNT ON;
declare @temp table
(
Name varchar(50),
Date_Assigned datetime,
Date_Completed datetime
)
INSERT INTO @temp
SELECT
'jon' , '8/17/2017' ,'8/20/2017' UNION SELECT ALL
'jon' , '9/10/2017' ,'9/11/2017' UNION SELECT ALL
'lucy', '8/5/2017' ,'8/5/2017' UNION SELECT ALL
'jon' , '8/19/2017' ,'9/27/2017'
select name, AVG(datediff(day, Date_Assigned, Date_Completed)) from @temp group by name
union select 'ALL', AVG(datediff(day, Date_Assigned, Date_Completed)) from @temp