首先,感谢您的关注。我通常会找到一个答案,所以我不会提出很多问题,但这使我想知道我做错了什么。
SQL Server 2008(尽管此服务器即将升级到2016)。
甚至不知道这是否可以完成,所以这就是为什么我要问。我正在尝试对订单进行排名,并为订单最多的人分配积分。最高的人获得10分,其次是9分,依此类推。
这就是我所拥有的
Salesperson Orders TotalSales
---------------------------------------
5695 270 23500
8475 310 46000
1287 105 9000
5412 475 75600
我想看的是这个
Salesperson Orders TotalSales Ranking
---------------------------------------------------
5412 475 75600 10
8475 310 46000 9
5695 270 23500 8
1287 105 9000 7
以此类推...
我正在尝试以下内容,但是我对RANK的了解全部
SELECT
Salesperson,
RANK() OVER (PARTITION BY Orders ORDER BY ORDERS DESC),
TotalSales
FROM
OrdersTable
非常感谢您的帮助!
答案 0 :(得分:4)
从PARTITION BY Orders
中删除DESC
和ORDER BY
,您应该会很好。
SELECT Salesperson
, RANK()OVER (ORDER BY ORDERS)
, TotalSales
FROM OrdersTable
此值与row_number
(他的答案中使用Yogesh)的区别在于,如果您有两个相同的值,则它们的排名相同,因此它们将被赋予相同的值。如果您希望排名没有差距,则可以使用dense_rank
这是列中重复值时这三个的比较。
declare @table table (val int)
insert into @table
values
(1),(1),(2),(3),(4),(4),(5)
select
val
,RN = row_number() over (order by val)
,[Rank] = rank() over (order by val)
,[DenseRank] = dense_rank() over (order by val)
from @table
结果
+-----+----+------+-----------+
| val | RN | Rank | DenseRank |
+-----+----+------+-----------+
| 1 | 1 | 1 | 1 |
| 1 | 2 | 1 | 1 |
| 2 | 3 | 3 | 2 |
| 3 | 4 | 4 | 3 |
| 4 | 5 | 5 | 4 |
| 4 | 6 | 5 | 4 |
| 5 | 7 | 7 | 5 |
+-----+----+------+-----------+
当值唯一时,您将在所有函数中获得相同的结果。
declare @tableUnique table (val int)
insert into @tableUnique
values
(1),(2),(3)
select
val
,RN = row_number() over (order by val)
,[Rank] = rank() over (order by val)
,[DenseRank] = dense_rank() over (order by val)
from @tableUnique
结果
+-----+----+------+-----------+
| val | RN | Rank | DenseRank |
+-----+----+------+-----------+
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | 3 | 3 | 3 |
+-----+----+------+-----------+
答案 1 :(得分:2)
使用select *
from (select *, row_number() over (order by Orders) Ranking
from OrdersTable
) t
order by Ranking desc;
函数:
Orders
如果您有相同的dense_rank
,则可以改用import random
a = random.sample(range(10),3)
number = int(str(random.randint(1,9)) + str(a[0]) + str(a[1]) + str(a[2]))
答案 2 :(得分:1)
赞:
;WITH cte AS
(
SELECT
Salesperson,
11 - RANK() OVER (ORDER BY ORDERS DESC) AS Ranking,
TotalSales
FROM
OrdersTable
)
SELECT *
FROM cte
ORDER BY Ranking DESC
答案 3 :(得分:0)
这很可能是您要寻找的东西
;WITH CTE (Salesperson, Orders, TotalSales) AS (
SELECT * FROM (
VALUES
(5695,270,23500),
(8475,310,46000),
(1287,105,9000),
(5412,475,75600)
) AS A (Column1, Column2, Column3)
)
SELECT Salesperson,
Orders,
TotalSales,
Ranking = RANK() OVER (
ORDER BY Orders
)
FROM CTE
ORDER BY ORDERS DESC
输出:
+-------------+--------+------------+---------+
| Salesperson | Orders | TotalSales | Ranking |
+-------------+--------+------------+---------+
| 5412 | 475 | 75600 | 4 |
| 8475 | 310 | 46000 | 3 |
| 5695 | 270 | 23500 | 2 |
| 1287 | 105 | 9000 | 1 |
+-------------+--------+------------+---------+
这会根据需要扩展或收缩,只需在基础RANK
上排序,然后在SELECT
上以降序重新排序。