Sql 嗯,请给我一个正确的解释。不要只是说有问题。这是你的问题。比较结果。它们不匹配。@MostyMostacho感谢您显示错误。我错过了在select查询中再次看到角色_1。我已经修改它,以适应用户的需要。 Sr No | TIMESTAMP
Sql 嗯,请给我一个正确的解释。不要只是说有问题。这是你的问题。比较结果。它们不匹配。@MostyMostacho感谢您显示错误。我错过了在select查询中再次看到角色_1。我已经修改它,以适应用户的需要。 Sr No | TIMESTAMP ,sql,sql-server,tsql,Sql,Sql Server,Tsql,嗯,请给我一个正确的解释。不要只是说有问题。这是你的问题。比较结果。它们不匹配。@MostyMostacho感谢您显示错误。我错过了在select查询中再次看到角色_1。我已经修改它,以适应用户的需要。 Sr No | TIMESTAMP | RoleInstance | Id 1 | 2012-03-14 12:00:00.000 | SLBMRole_IN_1 | 120007 2 | 20
嗯,请给我一个正确的解释。不要只是说有问题。这是你的问题。比较结果。它们不匹配。@MostyMostacho感谢您显示错误。我错过了在select查询中再次看到角色_1。我已经修改它,以适应用户的需要。
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 | 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
select *,rn = row_number() over (order by timestamp,roleinstance)
into #temp2
from #temp1
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
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