I have an order history file.
It has an Action column to store action performed on the order.
Order Id, Action, Date
1, Created, 8/1/10
1, Changed, 8/15/10
1, Changed, 9/1/10
What is the best t-sql to say
Give me the most recent changed date for all orders And if there is no
Changed status just give me the Created date.
Now I can imagine doing this by stringing the sql together and then
executing the sql string but is that the best way?
Thanks,
rod.
; WITH OrderStatuses (OrderId, ActionType, ActionDate, LastActionRank) AS (
SELECT OrderId, ActionType, ActionDate, RANK() OVER (PARTITION BY OrderId
ORDER BY OrderId, ActionDate Desc) As LastActionRank
FROM FooBar
)
SELECT OrderId, ActionType, ActionDate FROM OrderStatuses WHERE
LastActionRank = 1
Best regards,
--
MG.-
Mariano Gomez, MIS, MCP, PMP
Maximum Global Business, LLC
http://www.maximumglobalbusiness.com
The Dynamics GP Blogster at http://dynamicsgpblogster.blogspot.com
--
Erland Sommarskog, SQL Server MVP, esq...@sommarskog.se
Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000: http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
Might work
Best regards,
--
MG.-
Mariano Gomez, MIS, MCP, PMP
Maximum Global Business, LLC
http://www.maximumglobalbusiness.com
The Dynamics GP Blogster at http://dynamicsgpblogster.blogspot.com
"Erland Sommarskog" wrote:
> .
>
CREATE TABLE Order_Events
(order_nbr INTEGER NOT NULL,
event_date DATE NOT NULL,
order_action CHAR(6) NOT NULL
CHECK (order_action IN ('create', 'change', ..)),
PRIMARY KEY (order_nbr, event_date),
..);
We can assume that an order is created before it is changed, so:
SELECT order_nbr, MAX(event_date) AS last_change_date
FROM Order_Events
WHERE order_action IN ('create', 'change')
GROUP BY order_nbr;