1

I have an SQL table with some data like this, it is sorted by date:

+----------+------+
|   Date   | Col2 |
+----------+------+
| 12:00:01 | a    |
| 12:00:02 | a    |
| 12:00:03 | b    |
| 12:00:04 | b    |
| 12:00:05 | c    |
| 12:00:06 | c    |
| 12:00:07 | a    |
| 12:00:08 | a    |
+----------+------+

So, I want my select result to be the following:

+----------+------+
|   Date   | Col2 |
+----------+------+
| 12:00:01 | a    |
| 12:00:03 | b    |
| 12:00:05 | c    |
| 12:00:07 | a    |
+----------+------+

I have used the distinct clause but it removes the last two rows with Col2 = 'a'

3
  • 1
    What the result rule for a here? Commented May 7, 2016 at 16:35
  • It's helpful to tag database questions with both the appropriate software (MySQL, Oracle, DB2, ...) and version, e.g. sql-server-2014. Differences in syntax and features often affect the answers. Commented May 7, 2016 at 16:43
  • you need a query that will check the next row on every row hit Commented May 7, 2016 at 17:39

3 Answers 3

2

You can use lag (SQL Server 2012+) to get the value in the previous row and then compare it with the current row value. If they are equal assign them to one group (1 here) and a different group (0 here) otherwise. Finally select the required rows.

select dt,col2 
from (
select dt,col2,
case when lag(col2,1,0) over(order by dt) = col2 then 1 else 0 end as somecol
from t) x 
where somecol=0
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much.
0

If you are using Microsoft SQL Server 2012 or later, you can do this:

select  date, col2
from    (
            select  date, col2,
                    case when isnull(lag(col2) over (order by date, col2), '') = col2 then 1 else 0 end as ignore
            from    (yourtable)
        ) x
where   ignore = 0

This should work as long as col2 cannot contain nulls and if the empty string ('') is not a valid value for col2. The query will need some work if either assumption is not valid.

Comments

0

same as accepted answer (+1) just moving the conditions
assumes col2 is not null

select dt, col2 
from ( select dt, col2 
       lag(col2, 1) over(order by dt) as lagCol2 
       from t
     ) x 
where x.lagCol2 is null or x.lagCol2 <> x.col2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.