0

次のようなテーブルを想像してください。

create table test (depth integer, name text);

いくつかの行を追加します:

insert into test (depth, name)
values (0, "no indent"), (1, "single indent"), (2, "double indent");

depth次に、次のようなパラメーターに基づいて出力を作成します。

no indent
    single indent
        double indent

この場合のインデントは 4 つのスペースです (ただし、タブ文字のような興味深いインデントに変更できます)。

私の腸は次のようなことをしたい:

select '    ' * depth || name from test order by depth;

ただし、これはPostgresで爆発します。このような文字列の乗算は、Python では期待どおりに機能します。しかし、私は Postgres での同等の操作に慣れていません。他のデータベースの実装も興味深いでしょう。

4

2 に答える 2

2

使用lpad():

select lpad(name, (4 * depth) + length(name), ' ')
from test 
order by depth;

またはrepeat()プラス連結:

select repeat('_', 4 * depth) || name
from test 
order by depth;

http://www.postgresql.org/docs/current/static/functions-string.html

于 2013-03-15T21:59:08.307 に答える
1

Postgresqlにアクセスできませんが、SQLFiddleでは先頭のスペースが自動的に抑制されます。

スペースをアンダースコアに変更しましたが、機能します。

私のコード(に基づくREPEAT):

select REPEAT(REPEAT('_', 4), depth) || name as "Column" from test order by depth;

データを含むSQLFiddleへのリンク:http ://sqlfiddle.com/#!1 / 96f11 / 4

于 2013-03-15T22:08:27.097 に答える