我有一个用户表,其中包含金钱,级别和排名。
Id | money| ranking| level
---------------------------
1 |30000| 1 1
2 |20000| 2 3
3 |10000| 3 2
4 |50000| 4 2
我想根据用户级别(第一个过滤器)和金钱来更新排名字段。
这是更高级别的用户将始终排名更高。
这就是我希望更新后的表格如下:
Id | money| ranking| level
---------------------------
1 |30000| 4 1
2 |20000| 1 3
3 |10000| 3 2
4 |50000| 2 2
谢谢!
答案 0 :(得分:1)
作为旁注,我不会将此字段存储在数据库中 - 存储依赖于表中其他记录的值会使维护变得更加困难。
这是一个可用作视图或存储过程的查询:
SELECT
ID,
[money],
ROW_NUMBER() OVER (order by [level] desc, [money] desc) AS [ranking],
[level]
FROM myTable
如果您真的想要更新表,只需将查询作为更新的子查询:
UPDATE m1
SET ranking = m2.ranking
FROM myTable m1
INNER JOIN
(SELECT
ID,
ROW_NUMBER() OVER (order by [level] desc, [money] desc) ranking
FROM myTable) m2
ON m1.ID = m2.ID
答案 1 :(得分:1)
如果您只想选择,那么这里是查询:
select *, dense_rank() over (order by level desc, mony desc) as newranking from YourTable
如果你想更新,那么:
;with cte_toupdate (ranking, newranking)
as (
select ranking, dense_rank() over (order by level desc, mony desc) as newranking from YourTable
)
Update cte_toupdate set ranking = newranking
select * from YourTable
点击此处:http://sqlfiddle.com/#!3/8d6d3/10
注意:如果您想要唯一的排名,请使用Row_Number()而不是dense_rank()。
答案 2 :(得分:0)
CREATE TABLE #tt
(
id INT,
mony INT,
ranking INT,
levell INT
)
INSERT INTO #tt
VALUES (1,30000,1,1),
(2,20000,2,3),
(3,10000,3,2),
(4,50000,4,2)
UPDATE a
SET ranking = rnk
FROM #tt a
JOIN (SELECT Row_number()
OVER (
ORDER BY levell DESC, mony DESC) AS rnk,
*
FROM #tt) b
ON a.levell = b.levell
AND a.mony = b.mony