Firebirdユーザコンテキスト変数を使ったdense_rank()

[2009-11-24 Firebirdのユーザコンテキスト変数は、左から右に評価されないようで、以下は単にrownumになっていますorz 近日修正しますので、いましばらくお待ちください]

以前MySQLユーザ変数を使ったdense_rank()を紹介しましたが、
下記はそのFirebird版です。

Firebirdではrdb$set_context()が値ではなく、既存の設定あり(1), なし(0)になってしまうので、
Firebirdの組み込み関数に追加されたdecode()(Oracleと同じ)で、値を返すようにしています。

QL> --Like dense_rank()
SQL> select rdb$set_context('USER_SESSION', 'rnk', 0), rdb$set_context('USER_SESSION', 'preval', null) from rdb$database;

RDB$SET_CONTEXT RDB$SET_CONTEXT
=============== ===============
0 0

SQL> select case when cast(rdb$get_context('USER_SESSION', 'preval') as int) <> sal then cast(rdb$get_context('USER_SESSION', 'rnk') as int)
CON> ELSE decode(rdb$set_context('USER_SESSION', 'rnk', cast(rdb$get_context('USER_SESSION', 'rnk') as int) + 1),1,cast(rdb$get_context('USER_SESSION', 'rnk') as int)) END,
CON> decode(cast(rdb$set_context('USER_SESSION', 'preval', sal) as int), 1, sal,sal) from emp order by sal;

CASE CASE
============ ============
1 800
2 950
3 1100
4 1250
5 1250
6 1300
7 1500
8 1600
9 2450
10 2850
11 2975
12 3000
13 3000
14 5000