日期:2014-05-16 浏览次数:20740 次
DECLARE @t Table (
ID INT NOT NULL,
IP varchar(200) NOT NULL
)
INSERT @t
SELECT 1 AS [ID], 'a' AS [IP]
UNION ALL
SELECT 2 AS [ID], 'c' AS [IP]
UNION ALL
SELECT 3 AS [ID], 'b' AS [IP]
UNION ALL
SELECT 5 AS [ID], 'd' AS [IP]
UNION ALL
SELECT 6 AS [ID], 'a' AS [IP]
UNION ALL
SELECT 8 AS [ID], 'c' AS [IP]
UNION ALL
SELECT 9 AS [ID], 'b' AS [IP]
SELECT COUNT(t.ID)
FROM @t t , (SELECT L.ID AS LastID, ISNULL(S.ID,0) AS SecondID
FROM (SELECT TOP 1 ID, IP FROM @t t WHERE IP='a' ORDER BY ID DESC) L
OUTER APPLY (SELECT TOP 1 ID FROM @t t WHERE IP='a' AND ID<>L.ID ORDER BY ID DESC) S
) O
WHERE t.ID >=O.SecondID AND t.ID<O.LastID
DECLARE @t Table (
ID INT NOT NULL,
IP varchar(200) NOT NULL
)
INSERT @t
SELECT 1 AS [ID], 'a' AS [IP]
UNION ALL
SELECT 2 AS [ID], 'c' AS [IP]
UNION ALL
SELECT 3 AS [ID], 'b' AS [IP]
UNION ALL
SELECT 5 AS [ID], 'd' AS [IP]
UNION ALL
SELECT 6 AS [ID], 'a' AS [IP]
UNION ALL
SELECT 8 AS [ID], 'c' AS [IP]
UNION ALL
SELECT 9 AS [ID], 'b' AS [IP]
UNION ALL
SELECT 15 AS [ID], 'b' AS [IP]
UNION ALL
SELECT 18 AS [ID], 'd' AS [IP]
select r.IP,r2.Counts
from (
select IP,MAX(ID) as MaxId,MIN(id) MinId from @t
group by IP ) r
Outer Apply (
select COUNT(1) as Counts from @t where ID between r.MinId and r.MaxId -1
) r2