想象一下这样一个表:
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中的等效操作并不熟悉。其他的数据库实现也会很有趣。
发布于 2013-03-16 05:59:08
使用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-16 06:08:27
我没有访问Postgresql的权限,但在SQL上,前导空格会自动取消。
我改变了空格来加下划线,它起作用了。
我的代码(基于REPEAT):
select REPEAT(REPEAT('_', 4), depth) || name as "Column" from test order by depth;链接到包含您的数据的SQL Fiddle:http://sqlfiddle.com/#!1/96f11/4
https://stackoverflow.com/questions/15442649
复制相似问题