I need some SQL Server/database design help. I have a custom built admin for an ecommerce site where we manage our orders. During the life of an order, it can have many statuses ...
For example: In Process, Transmitted, Confirmed, Backordered, Shipped, Closed.
In my database I keep track of status changes in a table called Tracking. It's basically a log of status changes an order goes through and when. A sample data set for Order # 12111 might be something like:
Tracking
-------------
uid orderID statusID dateChanged
1 12111 5 7/1/2006
22 12111 21 7/1/2006
43 12111 7 7/3/2006
54 12111 8 7/5/2006
102 12111 7 7/8/2006
155 12111 15 7/15/2006
uid is the unique identifier for the record. StatusID is just a numeric unique identifier for the statusnames. The statusIDs don't progress sequentially in any way, meaning a statusID of 15 doesn't mean the order is further along in the process than a statusID of 7. DateChanged is the date the order was changed to that status.
Our accounting department wants to be able to do some kind of query to find out which orders were in a certain status on any given date or within a date range. For example, they might want to find all orders on Backorder (statusID=8) on 7/7/2006. What is the best way to do that?
Order 12111 would be one of those orders returned in the result set as it's status changed to backorder on 7/5/2006 and it didn't move to another status until 7/8/2006. How can I query for these records?
I'm hoping it can be done easily, but let's say it can't. What changes can I make to my Tracking table to be able to perform queries like that easily? Do I need to start keeping track of what the previous status is in each record? Something like:
Tracking
-------------
orderID oldstatusID statusID dateChanged
12111 1 5 7/1/2006
I really, really don't want to change the Tracking table because I know it would be a nightmare trying to back populate fields, etc. BUT if I have to, I will.
Help, please!
select T1.orderid
from tracking T1
where T1.uid = (select max(T2.UID) from tracking T2 where T2.date <= @DateCriteria and T1.OrderID = T2.OrderID)
and T1.StatusID = @StatusID
or something along those lines, you'll need a correlated subquery in anycase.
posted by blue_beetle at 2:09 PM on August 4, 2006