How to calculate order line number in SQL 2000
I am working with an ordering system that has two tables Order and OrderLine of pretty standard stuff. I want to work out the order line number for order lines relative to order, for example.
Orderidid linenumber
1 1 1
2 2 1
2 3 2
3 4 1
4 5 1
4 6 2
OrderLineId is the identity column. I don't want to store the row number as data in the database for two reasons. First, there are already many existing orders and lines in the system, and in retrospect adding data is a headache that I want to avoid. Second, if the user deletes a line, I will need to recalculate the line numbers for the whole order.
In SQL 2005 I can do it peasy easily using the ROW_NUMBER function.
Select Orderid, OrderLineid, ROW_NUMBER()
OVER(PARTITION BY Orderid ORDER BY Orderlineid) as LineNumber
FROM OrderLine
Is there anyway I can do this in SQL 2000?
The closest I've found is a ranking function (see below), but this is a counting of orders not rows.
SELECT x.Ranking, x.OrderId
FROM (SELECT (SELECT COUNT( DISTINCT t1.Orderid) FROM orderline t1 WHERE z.Orderid >= t1.Orderid)AS Ranking, z.orderid
FROM orderline z ) x
ORDER BY x.Ranking
source to share
IMHO figuring it out every time you need it can end up being more of a headache than it's worth. And while it can be painful to update the historical line numbers and store them in the database, you only do it once ... and then you just need to write the automation code later.
To deal with the deletion, you just need to add code to the existing delete routine and recalculate the line numbers for it.
source to share