日期:2014-05-17 浏览次数:20473 次
USE test
GO
-->生成表tb
if object_id(N'tb') is not null
drop table [tb]
Go
Create table [tb]([pid] smallint,[url] nvarchar(4),[searchkey] nvarchar(50),[time] datetime)
Insert into [tb]
Select 1,N'url1','friendlink','2012-12-1'
Union all Select 1,N'url2','','2012-12-2'
Union all Select 1,N'url3','','2012-12-3'
Union all Select 1,N'url1','','2012-12-4'
Union all Select 2,N'url3',N'djue','2012-12-5'
Union all Select 2,N'url4',N'dww','2012-12-6'
Union all Select 2,N'url2','','2012-12-7'
Union all Select 2,N'url3','','2012-12-8'
Union all Select 2,N'url1',N'ddj','2012-12-9'
Union all Select 2,N'url3','','2012-12-10'
------------------ date range:
DECLARE @startDate DATETIME,@endDate DATETIME
SELECT @startDate='2012-12-1'
,@endDate='2012-12-8'
------------------ statement 1:
SELECT
pid,url,searchkey,time
FROM tb AS a
WHERE ((ISNULL(searchkey,'') <> ''
AND searchkey <> 'friendlink'
) --- searchkey不全为空或friendlink
OR(NOT EXISTS(SELECT 1 FROM tb AS x
WHERE x.pid=a.pid
AND ISNULL(x.searchkey,'') <> ''
AND x.searchkey <> 'friendlink'
)
AND NOT EXISTS(SELECT 1 FROM tb AS x
WHERE x.pid=a.pid AND x.time < a.time
AND x.time >= @startDate
AND x.time <= @endDate
)
)
) --- searchkey都为空或friendlink
AND time >= @startDate
AND time <= @endDate
ORDER BY pid,time
------------------ statement 2:
IF OBJECT_ID('tempdb..#Result')IS NOT NULL
DROP TABLE #Result
SELECT
pid
,url
,searchkey
,CASE
WHEN searchkey='friendlink'
THEN NULL
ELSE searchkey
END AS searchkey2 --- friendlink 視為 NULL
,time
INTO #Result
FROM tb
WHERE time >= @startDate
AND time <= @endDate
SELECT
pid,url,searchkey,time
FROM #Result AS a
WHERE ISNULL(searchkey2,'') <>&n