SQL中的日期差异平均和分组

时间:2017-03-14 15:36:44

标签: sql sql-server

假设我有下表:

User | Date_start | Date_End | Task  
----------------------------------------  
 Al  | 1/11/17    | 1/14/17  | Dishes
 Al  | 1/09/17    | 1/15/17  | Paint
 Al  | 1/11/17    | 1/14/17  | Dishes
 Al  | 1/18/17    | 1/20/17  | Paint
Todd | 1/11/17    | 1/14/17  | Dishes
 Al  | 1/11/17    | 1/21/17  | Dishes
Todd | 1/10/17    | 1/17/17  | Paint
Todd | 1/11/17    | 1/14/17  | Dishes
Todd | 1/11/17    | 1/14/17  | Paint
 Al  | 1/11/17    | NULL     | Dishes

我要做的是平均完成任务栏中任务的日期
并按任务明确地对它们进行分组。但是,如果记录尚未完成(由' null'证明),我想从平均值计算中排除此记录。另外,我试图通过任务唯一地计算它们(同样,忽略具有date_end的' null'值的记录)。我希望获得这样的输出(" avg"数字肯定是关闭的,仅用于演示):

User | Count_of_Task | AVG_Time_to_Finish_In_Days | Task  
-----------------------------------------------------------  
 Al  |        3      |           4.2              | Dishes
 Al  |        2      |           4.0              | Paint
Todd |        2      |           2.6              | Dishes
Todd |        2      |           6.1              | Paint

我正在使用以下SQL:

Select s.user,
     COUNT(s.task) as count_of_task,
     AVG(DATEDIFF(dd,s.date_start,s.date_end)*1.0) as avg_time_to_finish_in_days,
     s.task
FROM dbo.stuff s
WHERE S.DATE_END IS NOT null
GROUP by s.task,
   s.user
HAVING AVG(DATEDIFF(dd,s.date_start,s.date_end)*1.0) <> 0
  and COUNT(s.task) <> 0

这个SQL没有正确地对任务进行分组,并且正在截断平均时间以完成,给我平均值只有小数位数为0(即6.000000)。

我正在使用SQL Server 2014。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

Declare @YourTable table ([User] varchar(25),Date_start  date,Date_End date,Task  varchar(25))
Insert Into @YourTable values
('Al','1/11/17','1/14/17','Dishes'),
('Al','1/09/17','1/15/17','Paint'),
('Al','1/11/17','1/14/17','Dishes'),
('Al','1/18/17','1/20/17','Paint'),
('Todd','1/11/17','1/14/17','Dishes'),
('Al','1/11/17','1/21/17','Dishes'),
('Todd','1/10/17','1/17/17','Paint'),
('Todd','1/11/17','1/14/17','Dishes'),
('Todd','1/11/17','1/14/17','Paint'),
('Al','1/11/17',NULL,'Dishes')

Select [User]
      ,Count_Of_Task = count(*)
      ,AVG_Time_to_Finish_In_Days  = convert(decimal(10,1),avg(datediff(DAY,Date_start,Date_End)+0.0))
      ,Task
 From  @YourTable 
 Where Date_End is not null
 Group By [User],Task
 Order by [User],Task

返回

User    Count_Of_Task   AVG_Time_to_Finish_In_Days  Task
Al      3               5.3                         Dishes
Al      2               4.0                         Paint
Todd    2               3.0                         Dishes
Todd    2               5.0                         Paint

答案 1 :(得分:1)

简单地添加WHERE子句就足够了

Select s.user,
     COUNT(s.task) as count_of_task,
     AVG(DATEDIFF(dd,s.date_start,s.date_end)*1.0) as avg_time_to_finish_in_days,
     s.task
FROM dbo.stuff s
WHERE s.date_end IS NOT NULL -- this should be sufficient
GROUP by s.task, s.user

请注意,在SQL Server中,您可以同时使用WHERE和HAVING与GROUP BY。 分组前的WHERE行为和分组后的HAVING。