Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: retrieve only the records whose value has changed

Tags:

sql

sql-server

Sorry for the nondescript title. I'll edit as we go along.

I have a table RateTable:

| Code   |  Date     |   Rate  |

  B001     2009-01-01   1.05
  B001     2009-01-02   1.05
  B001     2009-01-03   1.05
  B001     2009-01-04   1.05
  B001     2009-01-05   1.06
  B001     2009-01-06   1.06
  B001     2009-01-07   1.06
  B001     2009-01-08   1.07

There is an entry for each day, but the Rate rarely changes. Can I write a SQL query that will only return the rows in which a Rate change occurs? I'm using SQLServer

like image 522
Mike Sickler Avatar asked Mar 27 '09 14:03

Mike Sickler


People also ask

How do you find the value of a change in a column in SQL?

Using a SQL Server trigger to check if a column is updated, there are two ways this can be done; one is to use the function update(<col name>) and the other is to use columns_updated().

How do you get unique results back in SQL?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Which clause is used to retrieve filtered data?

The SQL WHERE clause is for filtering data or records. It's used to create a condition to extract only the necessary records needed.


1 Answers

If I read this right, you aren't looking for modified rows, but rows where the rate changes from the previous date. This query or something like it should do it:

SELECT  r1.Code, r1.Date, r1.Rate
FROM    RateTable r1
WHERE   r1.Rate <> (SELECT TOP 1 Rate
                   FROM    RateTable
                   WHERE   Date < r1.Date
                   ORDER BY Date DESC)
like image 172
David M Avatar answered Sep 21 '22 11:09

David M