»

SQLにおけるリナンバリング(その3)

SQL Server — タグ: , — enjoji.yasujiro @ 8:59 PM

その2からの続き

SQL Server2005から、順位付け関数(Over句)が用意されているので、これを利用すれば何も自己結合でゴキンゴキンにややこしいjoinなんかしなくても超簡単にリナンバリングは可能。

with test_Table as(
select code = 1301,Period = 200303 union all
select code = 1301,Period =200403 union all
select code = 1301,Period =200503 union all
select code = 1301,Period =200603 union all
select code = 1301,Period =200703 union all
select code = 1301,Period =200803 union all
select code = 2121,Period =200609 union all
select code = 2121,Period =200709 union all
select code = 2121,Period =200809 union all
select code = 7203,Period =200303 union all
select code = 7203,Period =200403 union all
select code = 7203,Period =200503 union all
select code = 7203,Period =200603 union all
select code = 7203,Period =200703 union all
select code = 7203,Period =200803
)select *
, num1 = rank() over(partition by code order by period)
, num2 = rank() over(order by Code ,period)
from test_Table


ちなみに、over句でpartition byを付けてあげると、グループ単位でナンバリング可能で、何も付けないと全体でナンバリングが可能らしい。これは便利だすな。

ただしこの順位付け関数は2005から実装されているので、SQL Server2000だと利用できません。そういう場合は、これとかこれでリナンバリングするしかありませんな。

さらにその4に続く

2 件のコメント »

  1. [...] その3に続く [...]

  2. [...] その3の続き [...]

このコメント欄の RSS フィード TrackBack URI

コメントをどうぞ

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2009 鎌倉橋日記 | powered by WordPress with Barecity