如何对不同的变量使用sql rank函数

时间:2017-03-20 18:40:51

标签: sql sql-server loops

我需要为每个国家代码,城市代码和年龄显示前10个数字,我混淆了如何使用等级功能? 我尝试使用光标为国家,城市和年龄创建3循环,但性能太糟糕了。 这就是我需要得到的结果(Original Image):

+ ----------- + -------- + --- + --- +
| CountryCode | CityCode | Age | Num |
+ ----------- + -------- + --- + --- +
| 1           | 2        | 23  | 67  |
| 1           | 2        | 24  | 56  |
| 1           | 2        | 25  | 44  |
| 1           | 6        | 23  | 89  |
| 1           | 6        | 24  | 77  |
| 1           | 7        | 23  | 90  |
| 1           | 2        | 23  | 67  |
| 1           | 2        | 24  | 56  |
| 1           | 2        | 25  | 44  |
| 1           | 6        | 23  | 89  |
| 1           | 6        | 24  | 77  |
| 1           | 7        | 23  | 90  |
+ ----------- + -------- + --- + --- +

2 个答案:

答案 0 :(得分:0)

如果您希望每个国家/地区代码,城市代码和年龄组合获得前10名,您可以使用dense_rank()

select *
from (
    select t.*,
        dense_rank() over (
            partition by countrycode,
            citycode,
            age order by num desc
            ) seqnum
    from your_table t
    ) t
where seqnum <= 10;

答案 1 :(得分:0)

只是为了演示row_number,rank和dense_rank在这种情况下的不同之处:

declare @tbl table 
(
countrycode int, citycode int, age int, num int
)

insert into @tbl
select 1, 7, 23, 70 union all 
select 1, 7, 23, 75 union all 
select 1, 7, 23, 75 union all 
select 1, 7, 23, 80

select *, 
ROW_NUMBER() over (partition by countrycode, citycode, age order by num) as row_number,
RANK() over (partition by countrycode, citycode, age order by num) as rank,
DENSE_RANK() over (partition by countrycode, citycode, age order by num) as dense_rank
from @tbl

+-------------+----------+-----+-----+------------+------+------------+
| countrycode | citycode | age | num | row_number | rank | dense_rank |
+-------------+----------+-----+-----+------------+------+------------+
|           1 |        7 |  23 |  70 |          1 |    1 |          1 |
|           1 |        7 |  23 |  75 |          2 |    2 |          2 |
|           1 |        7 |  23 |  75 |          3 |    2 |          2 |
|           1 |        7 |  23 |  80 |          4 |    4 |          3 |
+-------------+----------+-----+-----+------------+------+------------+