SQL Query to display records that dont match in consecutive rows

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ann VK
    New Member
    • Feb 2012
    • 6

    SQL Query to display records that dont match in consecutive rows

    I have a table with records like:
    ID End Price
    A 20060625 5.7025000000000 0000000
    A 20060725 5.7650000000000 0000000
    A 20060825 5.7043800000000 0000000
    A 20060925 5.7100000000000 0000000
    A 20061025 5.7000000000000 0000000
    A 20061125 5.7000000000000 0000000
    A 20061225 5.7300000000000 0000000
    A 20070125 5.7000000000000 0000000

    I want to get a query which would give the result as:
    ID End Price
    A 20060625 5.7025000000000 0000000
    A 20060725 5.7650000000000 0000000
    A 20060825 5.7043800000000 0000000
    A 20060925 5.7100000000000 0000000
    A 20061025 5.7000000000000 0000000
    A 20061225 5.7300000000000 0000000
    A 20070125 5.7000000000000 0000000

    The reason is that the 5th and 6th record had the same price. Then I dont want to display that. So in other words i want to be able to compare the prices between each consecutive rows and return only the rows that dont match. Is it possible to do it in a single query?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You could use the row_number function to number the rows and then join it to itself to get the previous row to see if they match.

    Comment

    • Ann VK
      New Member
      • Feb 2012
      • 6

      #3
      Originally posted by Rabbit
      You could use the row_number function to number the rows and then join it to itself to get the previous row to see if they match.
      Thanks you so much for your suggestion. I tried this way and it worked!!

      Just in case someone wants to see the query, i created a view for this with query:

      with cte_rownum (Ranks,ID,End_D ate,Price) as
      (select rank() over (order by ID,End_Date) as rank,
      ID,End_Date,Pri ce from PriceTable)

      select a.* from cte_rownum a inner join cte_rownum b on a.ranks = 1 where a.Price <> b.Price
      union
      select b.* from cte_rownum a inner join cte_rownum b on a.ranks = b.ranks-1 where a.Price <> b.Price

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Not a problem Ann, good luck.

        Comment

        Working...