How to skip current records if previous records is same

Viewed 34

I want to fetch records from SQL but condition is that if Previous records is same as current records then its should skip current records but after some records records repeat in data it should be taken only once time if same condition occurs current records same as previous its should skip that records

Please check below image https://imgur.com/a/GknMm3N

2 Answers

I searched & placed our tables data to get the results.

    SELECT url_rec,record_timestamp
FROM (
    SELECT *
         , LAG(url_rec) OVER (ORDER BY url_rec) AS prev_title
    FROM raw_activity_log
) AS x
WHERE url_rec <> prev_title ORDER BY id

As LAG isn't a function in SQL-Server-2008 you can also use the ROW_NUMBER function with a self join.

DECLARE @table TABLE( 
    [ID] int IDENTITY(1,1) 
    ,[NAME] varchar(3) 
); 

INSERT INTO @table 
    VALUES ('XYZ'), ('XYZ'), ('XYZ'), ('PQR'), ('PQR'), ('RST'), ('RST'), ('XYZ')

SELECT 
    T1.[ID] 
    ,T1.[NAME] 
FROM (
    SELECT 
        [ID] 
        ,[NAME] 
        ,ROW_NUMBER() OVER (ORDER BY [ID]) AS 'RowNum' 
    FROM @table T 
) T1 
LEFT JOIN (
    SELECT 
        [ID] 
        ,[NAME] 
        ,ROW_NUMBER() OVER (ORDER BY [ID]) AS 'RowNum' 
    FROM @table T 
) T2 
    ON T2.[RowNum] + 1 = T1.[RowNum] 
WHERE T1.[NAME] <> ISNULL(T2.[NAME], '') 
ORDER BY T1.[ID]; 

Not a prefect answer but so long as you don't have a large number of records it will do the trick. Should return :

ID NAME
1 XYZ
4 PQR
6 RST
8 XYZ
Related