|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Monday, April 22, 2013 10:26 PM
Points: 9,
Visits: 22
|
|
|
|
|
|
Ten Centuries
      
Group: General Forum Members
Last Login: Wednesday, March 27, 2013 3:22 PM
Points: 1,276,
Visits: 1,112
|
|
|
|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Monday, April 22, 2013 10:26 PM
Points: 9,
Visits: 22
|
|
Hi Mike C
thanks for remind for such cool sequential ordering
|
|
|
|
|
Mr or Mrs. 500
      
Group: General Forum Members
Last Login: Friday, July 06, 2012 9:12 AM
Points: 500,
Visits: 183
|
|
|
|
|
|
SSC Rookie
      
Group: General Forum Members
Last Login: Wednesday, May 15, 2013 7:14 AM
Points: 40,
Visits: 33
|
|
Couldn't this same query:
UPDATE Products SET UnitPrice = 0.9 * UnitPrice WHERE ProductID IN ( SELECT ProductID FROM( SELECT ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS Number, ProductID FROM Products) AS B WHERE Number < = 10 )
Be written in SQL2k (or SQL2005 for that matter) using TOP instead of ROW_NUMBER? This query even looks simpler and easier to understand:
UPDATE Products SET UnitPrice = 0.9 * UnitPrice WHERE ProductID IN ( SELECT TOP 10 ProductID FROM Products ORDER BY UnitPrice DESC )
|
|
|
|
|
Ten Centuries
      
Group: General Forum Members
Last Login: Wednesday, March 27, 2013 3:22 PM
Points: 1,276,
Visits: 1,112
|
|
What's more difficult is something like this: UPDATE Products SET UnitPrice = 0.9 * UnitPrice WHERE ProductID IN ( SELECT ProductID FROM( SELECT ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS Number, ProductID FROM Products) AS B WHERE Number % 10 = 0 ) Or UPDATE Products SET UnitPrice = 0.9 * UnitPrice WHERE ProductID IN ( SELECT ProductID FROM( SELECT ROW_NUMBER() OVER (ORDER BY UnitPrice DESC) AS Number, ProductID FROM Products) AS B WHERE (Number >= 10 AND Number < 20) OR (Number >= 50 AND Number < 60) )
|
|
|
|
|
SSC Rookie
      
Group: General Forum Members
Last Login: Wednesday, May 15, 2013 7:14 AM
Points: 40,
Visits: 33
|
|
| Are you saying that in the case of "discount the price for the top 10 most expensive products" that using TOP would indeed be a better choice, but for more complicated requirements ROW_NUMBER provides a valuable alternative to complicated queries?
|
|
|
|
|
Ten Centuries
      
Group: General Forum Members
Last Login: Wednesday, March 27, 2013 3:22 PM
Points: 1,276,
Visits: 1,112
|
|
| Absolutely. The example given for the Top 10 was too simple to benefit (unless of course you're trying to port something to/from a system that does not support the TOP keyword). If you want to sample values from every 10th item, or need to grab the #s 11-20; or #s 31-40 (or combinations, etc.), ROW_NUMBER is much easier to use (and often considerably faster) than most alternatives. The alternatives often include a lot of complex self-joins to "number" the rows to achieve this same effect.
|
|
|
|