Re: Renumber a field which a order using UPDATE

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: David Portas (REMOVE_BEFORE_REPLYING_dportas_at_acm.org)
Date: 01/14/05


Date: Fri, 14 Jan 2005 08:52:36 -0000

You can do this:

UPDATE Fruits
 SET rank =
  (SELECT COUNT(*)
   FROM Fruits AS F
   WHERE F.rank < Fruits.rank
    OR (F.rank = Fruits.rank
     AND F.fruit <= Fruits.fruit))

However, it's probably better not to store the rank at all, otherwise you
have to update all the ranks whenever the table changes. You can instead
calculate the Rank in a query:

SELECT F1.fruit, COUNT(*) AS rank
 FROM Fruits AS F1
 JOIN Fruits AS F2
  ON F1.rank > F2.rank
   OR (F1.rank = F2.rank
    AND F1.fruit >= F2.fruit)
 GROUP BY F1.fruit

-- 
David Portas
SQL Server MVP
--


Relevant Pages

  • Re: making the keys of a hash from parameters collected from a form
    ... I have the need to prioritize a number of items from a list and then ... Instead, use the same name, say 'rank', for all the textfields. ... make a whole bunch of changes every time you change the list of fruits. ... use CGI qw; ...
    (comp.lang.perl.misc)
  • Re: Ranking - More
    ... > should rank in terms of display. ... > INTO #tempRank from content; ... BY clause in either of the previous two select statements. ... set rank = q.newrank ...
    (microsoft.public.inetserver.asp.db)