SQL - timestampdiff上的条件

时间:2016-02-03 16:29:31

标签: sql average timestampdiff

我想获得门票解决时间的平均时间 从州'billet ouvert'到州'résolu'

Table Sample

我试过的查询:

查询1:

 SELECT
   title AS 'Etat', ticket_id, user_id,
   AVG(TIMESTAMPDIFF(HOUR,
                     helpdesk_followup.date having title in ('billet ouvert'),
                     helpdesk_followup.date having title in ('résolu'))
   ) AS 'moyenne'
  FROM helpdesk_followup        
 GROUP BY user_id;

查询2:

 SELECT
   title AS 'Etat', ticket_id, user_id,
   AVG(TIMESTAMPDIFF(HOUR,
                     helpdesk_followup.date as date1,
                     helpdesk_followup.date as date2)
   ) AS 'moyenne'
  FROM helpdesk_followup
 WHERE date1 having title IN 'résolu'
   AND date2 having title IN 'billet ouvert'
 GROUP BY user_id;

但是这些查询没有得到我需要的结果。如何向timestampdiff添加条件?

1 个答案:

答案 0 :(得分:0)

第一列是起始事件,第二列是结束事件。 我在几分钟内完成了平均值。这个SQL可以解决标题问题,你可能希望将其调整为更加鲜明的标题

select a.title, b.title, avg(DateDiff(MINUTE, '00:00:00', b.[date] ) - DateDiff(MINUTE, '00:00:00', a.[date] ) ) from
         (select *, row_number() over (order by [date]) hf from helpdesk_followup) a
    join (select *, row_number() over (order by [date]) hf from helpdesk_followup) b on (a.hf=b.hf-1)
group by
    a.title, b.title

我遗漏了查询中的user_id,因为我不确定您是否希望使用该字段将其分解。

希望你能够开始修改你需要的东西

编辑:以下是我用于查询的测试数据

CREATE TABLE [dbo].[helpdesk_followup](
    [title] [varchar](50) NULL,
    [ticket_id] [int] NULL,
    [user_id] [int] NULL,
    [date] [datetime] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[helpdesk_followup] ([title], [ticket_id], [user_id], [date]) VALUES (N'billet ouvert', 133, NULL, CAST(N'2015-07-22 15:36:00.000' AS DateTime))
GO
INSERT [dbo].[helpdesk_followup] ([title], [ticket_id], [user_id], [date]) VALUES (N'résolu', 133, 19, CAST(N'2015-07-23 15:36:00.000' AS DateTime))
GO
INSERT [dbo].[helpdesk_followup] ([title], [ticket_id], [user_id], [date]) VALUES (N'billet ouvert', 134, 15, CAST(N'2015-07-23 15:36:00.000' AS DateTime))
GO
INSERT [dbo].[helpdesk_followup] ([title], [ticket_id], [user_id], [date]) VALUES (N'résolu', 134, 21, CAST(N'2015-07-27 15:36:00.000' AS DateTime))
GO