表:哪个角色实例更改了时间
Sr No | TIMESTAMP | RoleInstance | Id
1 | 2012-03-14 12:00:00.000 | SLBMRole_IN_1 | 120007
2 | 2012-03-14 12:01:00.000 | SLBMRole_IN_1 | 120007
3 | 2012-03-14 12:02:00.000 | SLBMRole_IN_1 | 120007
4 | 2012-03-14 12:24:00.000 | SLBMRole_IN_0 | 120007
5 | 2012-03-14 12:25:00.000 | SLBMRole_IN_0 | 120007
5 | 2012-03-14 12:26:00.000 | SLBMRole_IN_0 | 120007
6 | 2012-03-14 12:27:00.000 | SLBMRole_IN_1 | 120007
7 | 2012-03-14 12:28:00.000 | SLBMRole_IN_1 | 120007
下面基于上表的新表,以便在RoleInstance中更改时获取值
RoleInstance | Start time | End Time
SLBMRole_IN_1 | 1st row Time stamp | 3rd row time stamp(bcz 4th row RoleInstance changed)
SLBMRole_IN_0 | 4th row time stamp | 5th row time stamp
SLBMRole_IN_1 | 6th row time stamp | …so on and so forth
所以基本上当RoleInstance改变时,我需要得到相同的开始时间和结束时间 我可以获得一个查询来实现上面的输出表吗?
答案 0 :(得分:0)
select *,rn = row_number() over (order by timestamp,roleinstance)
into #temp2
from #temp1
我发现srno正在重复,因此我先添加了行号
select a.*
from #temp2 a
where rn = 1
union all
select a.*
from #temp2 a, #temp2 b
where a.rn+1 = b.rn
and a.roleinstance <> b.roleinstance
union all
select a.*
from #temp2 a, #temp2 b
where a.rn = b.rn +1
and a.roleinstance <> b.roleinstance
order by a.rn
添加行号后,此查询将提供所需的结果
答案 1 :(得分:0)
我在这里假设SrNo是顺序的。我这样说是因为SrNo 5已被复制。以下查询将解决这个问题:
CREATE TABLE #temp (SrNo INT, DTS DATETIME, RoleInstance VARCHAR(30), Id INT)
INSERT INTO #temp VALUES
(1,'2012-03-14 12:00:00.000','SLBMRole_IN_1',120007),
(2,'2012-03-14 12:01:00.000','SLBMRole_IN_1',120007),
(3,'2012-03-14 12:02:00.000','SLBMRole_IN_1',120007),
(4,'2012-03-14 12:24:00.000','SLBMRole_IN_0',120007),
(5,'2012-03-14 12:25:00.000','SLBMRole_IN_0',120007),
(6,'2012-03-14 12:26:00.000','SLBMRole_IN_0',120007),
(7,'2012-03-14 12:27:00.000','SLBMRole_IN_1',120007),
(8,'2012-03-14 12:28:00.000','SLBMRole_IN_1',120007)
WITH Logins AS (
SELECT t2.SrNo, ROW_NUMBER() OVER (ORDER BY t2.SrNo) AS join_no, t2.RoleInstance, t2.DTS, t2.Id
FROM #temp t2 LEFT JOIN #temp t1 ON t2.SrNo = t1.SrNo +1
WHERE t1.RoleInstance <> t2.RoleInstance OR t1.RoleInstance IS NULL),
Logouts AS (
SELECT t1.SrNo, ROW_NUMBER() OVER (ORDER BY t1.SrNo) AS join_no, t1.RoleInstance, t1.DTS, t1.Id
FROM #temp t1 LEFT JOIN #temp t2 ON t2.SrNo = t1.SrNo +1
WHERE t1.RoleInstance <> t2.RoleInstance OR t2.RoleInstance IS NULL)
SELECT i.Id, i.RoleInstance, i.SrNo AS InSrNo, i.DTS AS InDTS, o.SrNo AS OutSrNo, o.DTS AS OutDTS
FROM Logins i INNER JOIN Logouts o ON i.join_no = o.join_no
两个公用表表达式(Logins和Logouts)分别检索给定RoleInstance的更改和给定RoleInstance的更改。第一个执行从第二个到第一个后续记录的左连接,允许两个中的第一个为空以检索第一个登录。第二个反过来,检索最后一次注销。然后将它们连接到由ROW_NUMBER()函数生成的密钥。