2017-03-20 3 views
0

各国コード、都市コード、年齢別にトップ10を表示する必要がありますが、どのようにランク関数を使用できますか? 国、都市、年齢の3ループを作成してカーソルを試しましたが、パフォーマンスが悪かったです。 私は結果(Original Image)を取得する必要がありますどのようにこの本:異なる変数にSQLランク関数を使用する方法

+ ----------- + -------- + --- + --- + 
| 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 | 
+ ----------- + -------- + --- + --- + 

答えて

0

あなたが国番号、citycodeと年齢の組み合わせごとに上位10 NUMSを取得したい場合は、あなただけに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; 
+0

row_number()をrank()に置き換えます。これにより、同じ値がtiesに割り当てられます。この場合、row_number、rankおよびdense_rankは次のようになります。 –

+0

@MaxSzczurek - 'dense_rank'がより適していると思います。 – GurV

+0

はい、おそらくdense_rankです。明確にするために、同点がある場合、dense_rank()は値をスキップしませんが、rank()は値をスキップしません。たとえば、ランク付けされたnum値が70,75,75,80の場合、dense_rankはそれらを1,2,2,3とランク付けしますが、ランクは1,2,2,4とランク付けされ、ネクタイがあったため3をスキップします#2のために。 –

0

を使用することができます

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 | 
+-------------+----------+-----+-----+------------+------+------------+ 
+0

出力テーブルフォーマッタについてはhttps://senseful.github.io/web-tools/text-table/ありがとうございます。 –