我正在尝试创建一个SQL查询,该查询将根据创建的日期对记录进行排名,然后在记录交互(请求和响应)的表中按eventId进行分组
日期计算将从当时创建的响应日期派生 - 请求日期已创建,但可能有多个响应和请求实例
我设法做了第一部分,即识别和排列事件,但无法确定如何分组;请参阅下面的查询和结果集:
WITH rows
AS (
SELECT ID,
IncidentId,
Cust,
Channel,
TTypeID,
DateCreated,
RANK() OVER (PARTITION BY IncidentId ORDER BY Id) AS 'rownum',
ROW_NUMBER() OVER (PARTITION BY IncidentId ORDER BY DateCreated) AS Counts
FROM [dbo].[Thread]
WHERE TypeId IN (3, 4, 2, 1)
)
SELECT *
FROM (
SELECT DISTINCT a.ID,
a.incidentId,
a.Channel,
a.rownum,
a.TypeID,
a.datecreated
FROM rows a
JOIN rows b
ON a.incidentId = b.incidentId
WHERE a.TypeId IN (3, 4, 2)
) AS base
ID Incident Channel Rownum Type DateCreated
24108571 9436560 Form 1 3 2015-04-22 13:41:29.000
24109189 9436560 E-mail 2 2 2015-04-22 13:48:21.000
24109788 9436560 Form 3 3 2015-04-22 13:49:39.000
24109789 9436560 Email 4 2 2015-04-22 13:50:37.000
我希望能够再次对结果进行排名,以便确定请求响应的数量。
输出应如下:
ID Incident Channel Rownum Type DateCreated WaitTimeGrouping
24108571 9436560 Form 1 3 2015-04-22 13:41:29.000 0
24109189 9436560 E-mail 2 2 2015-04-22 13:48:21.000 1
24109788 9436560 Form 3 3 2015-04-22 13:49:39.000 0
24109789 9436560 Email 4 2 2015-04-22 13:50:37.000 2
答案 0 :(得分:0)
让您入门的示例选项可能如下所示:
SELECT
req.Incident,
MAX( resp.DateCreated - req.DateCreated ),
MIN( resp.DateCreated - req.DateCreated ),
AVG( resp.DateCreated - req.DateCreated )
FROM Thread req
INNER JOIN Thread resp
ON req.Incident = resp.Incident
AND resp.Rownum = req.RowNum+1
WHERE req.Type = 3 -- "Request"?
AND resp.Type = 2 -- "Response"?
GROUP BY req.Incident
请注意,我们只是假设响应的Rownum
始终是请求的Rownum
+ 1。如果无法保证,则需要另一个(子)查询来查找请求和响应记录之间的匹配。