Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL to determine "out of sequence" records

I am using SQL server and I need to determine records that are "out of sequence" from a table.

I'll explain through an example. I have the following table structure:

OrderNumber OrderStatus EventDateTime
0001522989  22          2014-04-14 05:49:25.4414243
0001522989  26          2014-04-14 05:51:16.7047485
0001522989  23          2014-04-14 05:51:17.8602798
0001522990  23          2014-04-14 05:51:19.9603575
0001522990  24          2014-04-14 05:52:06.5803494
0001522990  24          2014-04-14 05:52:06.5803494

Now I need to produce a list of OrderNumbers that were sent "out of order". So in this example, the list will contain only one value: "0001522989".

Order 0001522990 was sent in the correct sequence (first status 23, then status 24 and then again status 24 (this doesn't count as "out of sequence")).

Order 0001522989 was not sent in the correct sequence (first status 22, then status 26 and then status 23).

Any idea on how I can accomplish this?

I added the possibility of an order to send out the same status twice in a row (this shouldn't count as "out of sequence")

Thanks in advance.

like image 491
Rise_against Avatar asked Apr 17 '14 09:04

Rise_against


People also ask

How do you find sequential numbers in SQL?

To number rows in a result set, you have to use an SQL window function called ROW_NUMBER() . This function assigns a sequential integer number to each result row.

How can I get last 5 records from a table?

METHOD 1 : Using LIMIT clause in descending orderof specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending. Since Employee table has IDs, we will perform ORDER BY ID in our query.

How can I get last 10 records from a table?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.


1 Answers

In SQL Server 2008 onwards...

SELECT
  OrderNumber
FROM
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY OrderNumber ORDER BY OrderStatus, EventDateTime  )   AS sequenceCorrect,
    ROW_NUMBER() OVER (PARTITION BY OrderNumber ORDER BY              EventDateTime)   AS sequenceActual
  FROM
    yourTable
)
  AS yourTableSequenced
WHERE
  sequenceCorrect <> sequenceActual
GROUP BY
  OrderNumber
ORDER BY
  OrderNumber


EDIT : Oops, I forgot the WHERE clause, should work now ;)

like image 138
MatBailie Avatar answered Oct 24 '22 18:10

MatBailie