0

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://i.stack.imgur.com/r9eR3.jpg

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

1

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
  • Yes. Your query is perfect. I have again some issue actually I have to do time difference between to visited URL instead of XYZ, PQR, RST there will be url of any website and next column is time_stamp. I have to calculated how much time user spend on specific URL and you do something for me. – Rakesh Thakre Sep 19 '22 at 11:15
0

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