1

I have a table with with two fields: ID field (FID) as primary key and Qty both are integers. I need to query this table and add two additional fields as sequence serial using the QTY field so I can get results like this:

table1
-------------------------------------
ID   Qty   range_begin   range_end
50   2         1           2
53   1         3           3
65   3         4           6
67   2         7           8     

range_begin field start at 1, next record should be range_end + 1. And range_end = last range_end + Qty

I tried to write it using context variables Like this

I set all variables to null first

rdb$set_context('USER_TRANSACTION', 'range_end', null);
rdb$set_context('USER_TRANSACTION', 'range_begin', null);

Than I start the query:

Select 
  rdb$get_context('USER_TRANSACTION', 'range_begin'),
  rdb$set_context('USER_TRANSACTION', 'range_begin', COALESCE(CAST(rdb$get_context('USER_TRANSACTION', 'range_end') AS INTEGER), 0) + 1)),

  rdb$get_context('USER_TRANSACTION', 'range_end'),
  rdb$set_context('USER_TRANSACTION', 'range_end', COALESCE(CAST(rdb$get_context('USER_TRANSACTION', 'range_end') AS INTEGER), 0) + Qty)),

  Qty
  from table1 where ... 

But I did not able to get the correct sequence. I also tried to add more variables and other things but none worked for me so how this should be done so I can use single select query ?

I am using FireBird 2.5 and it is not necessary for the answer to use context variables.

4

1 に答える 1

2

基本的に、あなたが望むものは

SELECT t.ID, t.QTY, 
  ((select coalesce(sum(qty),0) from table1 a where a.ID < t.ID) + 1) as RANGE_BEGIN,
  ((select coalesce(sum(qty),0) from table1 a where a.ID < t.ID) + t.qty) as RANGE_END
FROM table1 t

大きなテーブルの場合、これは遅くなる可能性があるため、計算フィールドの代わりに、永続フィールドを使用してトリガーで範囲値を計算することをお勧めします...データがどのように変化するかなどによって異なります.

于 2013-10-08T15:47:55.243 に答える