简体   繁体   中英

Best way to insert ranking (SQL database with php)

UserID  Rank  TotalRevenue  TotalDishesSold
1550    0     908           45
1141    0     985           67
1402    0     637           34
1063    0     736           89 
1204    0     26            78

Hi, this is the first time I am doing SQL using php. What is the best way/efficient to sort the database according to TotalRevenue then TotalDishesSold and insert a rank to each user? I will have 100k of user.

you can order using ROW_NUMBER()

SELECT UserID, ROW_NUMBER() OVER (ORDER BY TotalRevenue DESC, TotalDishesSold DESC), 
       TotalRevenue, TotalDishesSold
FROM   TableName

Use Temp Table to store the UserID and Rank. Then join with your table and update the Rank

Temp table

INSERT INTO @Temp (UserID, Rank)
SELECT UserID, ROW_NUMBER() OVER (ORDER BY TotalRevenue DESC, TotalDishesSold DESC)
FROM   TableName

Update your table

UPDATE  T SET
        T.Rank = T1.Rank
FROM    TableName AS T INNER JOIN
        @Temp AS T1 ON T1.UserID = T.UserID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM