我们正在尝试计算每次访问的时间。使用LAG和LEAD,我可以确定何时读取标签以进行新的访问。 lRead
栏中的N / A标识访问的第一个读取项。 nRead
栏中的N / A标识访问的最后一次读取。我想对每次访问的读取计数(将第一个读取分组,直到最后一个读取分组,由N / A标识)。
dataRead
表数据
tagID | locID | direction | laneGroup | messageTime
-------+-------+-----------+-------------+-------------
466 | T18 | In | InSecurity | 7:54 AM
466 | T18 | In | InOffice | 7:59 AM
466 | T18 | Out | OutOffice | 8:37 AM
466 | T18 | Out | OutSecurity | 8:38 AM
466 | T18 | Out | OutSecurity | 8:39 AM
466 | T18 | In | InSecurity | 3:06 PM
466 | T18 | Out | OutSecurity | 3:26 PM
466 | T18 | Out | OutSecurity | 3:27 PM
466 | T18 | In | InSecurity | 3:35 PM
466 | T18 | Out | OutOffice | 3:58 PM
466 | T18 | Out | OutSecurity | 4:02 PM
466 | T18 | Out | OutSecurity | 4:03 PM
下面是必须帮助我在下一个读取和最后一个读取列中使用N / A值识别新访问的SQL。
WITH Level1 -- Get the data
AS ( SELECT
tagID,
locID,
direction,
laneGroup,
messageTime,
LAG(direction, 1, 'N/A')
OVER ( PARTITION BY CONCAT(tagID,locID)
ORDER BY messageTime) AS lRead,
LEAD(direction, 1, 'N/A')
OVER ( PARTITION BY CONCAT(tagID,locID)
ORDER BY messageTime) AS nRead
FROM
dataRead
Level2 -- Identify end of visit and beginning of new visit
AS ( SELECT
tagID,
locID,
direction,
laneGroup,
messageTime,
CASE WHEN direction = 'In' AND lRead= 'Out' THEN 'N/A' ELSE lRead
END lRead,
CASE WHEN direction = 'Out' AND nRead= 'In' THEN 'N/A' ELSE nRead
END nRead
FROM
Level1
),
Level3 -- Get times
AS ( SELECT
tagID,
mtoID,
direction,
laneGroup,
messageTime,
lRead,
nRead,
CASE
WHEN nextEvent = 'N/A' THEN NULL
ELSE DATEDIFF(SECOND, messageTime,
LEAD(messageTime)
OVER ( PARTITION BY CONCAT(tagID,mtoID)
ORDER BY messageTime ))
END AS toSeconds,
CASE
WHEN lastEvent = 'N/A' THEN NULL
ELSE DATEDIFF(SECOND, messageTime,
LAG(messageTime)
OVER ( PARTITION BY CONCAT(tagID,mtoID)
ORDER BY messageTime )) * -1
END AS fromSeconds
FROM Level2
)
SELECT
ROW_NUMBER() OVER (PARTITION BY CONCAT(tagID,mtoID) ORDER BY messageDateTime) as dReads,
tagID,
locID,
laneGroup,
lRead,
nRead,
toSeconds,
fromSeconds
FROM
Level3
ORDER BY
mtoID,
tagID,
messageTime;
我想对每次访问进行分组并计算每次访问的读取次数(我需要使用SQL创建列visitCnt)。
dReads | tagID | locID | laneGroup | lRead | nRead | visitCnt
--------+-------+-------+-------------+-------+-------+----------
1 | 466 | T18 | InSecurity | N/A | In | 1
2 | 466 | T18 | InOffice | In | Out | 2
3 | 466 | T18 | OutOffice | In | Out | 3
4 | 466 | T18 | OutSecurity | Out | Out | 4
5 | 466 | T18 | OutSecurity | Out | N/A | 5
6 | 466 | T18 | InSecurity | N/A | Out | 1 <-- New Visit
7 | 466 | T18 | OutSecurity | In | Out | 2
8 | 466 | T18 | OutSecurity | Out | N/A | 3
9 | 466 | T18 | InSecurity | N/A | Out | 1 <-- New Visit
10 | 466 | T18 | OutOffice | In | Out | 2
11 | 466 | T18 | OutSecurity | Out | Out | 3
12 | 466 | T18 | OutSecurity | Out | N/A | 4