2017-03-02 53 views
0

我需要通過一個SQL查詢生成以下序列。通過SQL序列

party1 party2 
1 0 
2 1 
3 3 
4 5 
5 8 
6 11 
7 14 
8 17 
9 21 
10 25 

我們應該輸入party1並且應該生成party2。

+1

它是高度dbms特定的。 – zerkms

+3

這是作業嗎? – cha

+0

'party1'甚至與輸出有關,除了可能的詞數的起始數量? –

回答

0

根據to the link該shA.t貼,其公式爲:

n*ceiling(log_2 n) - 2^ceiling(log_2(n)) + 1 

在Postgres裏這可以寫爲:

select n as party1 
     (n*ceiling(log(2.0, n)) - 2^ceiling(log(2.0, n)) + 1)::int as party2 
from generate_series(1,10) x(n); 

作爲問題僅與sql標記以下是ANSI SQL(log()函數除外):

with recursive numbers (n) as (
    values (1) 
    union 
    select p.n + 1 
    from numbers p 
    where p.n <= 9 
) 
select n, cast(n*ceiling(log(2.0, n)) - power(2,ceiling(log(2.0, n))) + 1 as integer) 
from numbers; 

對於不支持(遞歸)公用表表達式的數據庫,只需創建數字表:

create table numbers (n integer); 
insert into numbers (n) 
values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10); 
+0

我是否必須使表格編號? – user3296651

+0

@ user3296651:這是生成數字的公用表表達式。你不需要創建表 –

+0

我收到錯誤。如選擇關鍵字或預期水木清華「(」或TRANSACTIONTIME關鍵字之間或「(」 A延遲寫關鍵字和值關鍵字 – user3296651