在sqlite中如何使用填充连接字符串

240

我在 sqlite 表中有三列:

    Column1    Column2    Column3
    A          1          1
    A          1          2
    A          12         2
    C          13         2
    B          11         2

我需要选择 Column1-Column2-Column3(例如 A-01-0001)。我想要用 - 填充每一列。


可能是重复问题:https://dev59.com/83A65IYBdhLWcg3w6DFO - Jon Adams
3个回答

420

|| 运算符是“连接”运算符-它将其操作数的两个字符串连接在一起。

来自http://www.sqlite.org/lang_expr.html

对于填充,我使用的看起来有些欺骗的方法是从目标字符串开始,比如 '0000',连接 '0000423',然后对 '0423' 使用 substr(result, -4, 4)。

更新:看起来 SQLite 没有 "lpad" 或 "rpad" 的本地实现,但你可以在这里执行类似于我提出的操作:http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/

-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable

select substr('0000000000' || mycolumn, -10, 10) from mytable

-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable

select substr(mycolumn || '0000000000', 1, 10) from mytable

这是它的外观:

SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4)

它产生了

"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"

10
通常情况下,任何涉及 NULL 的标量操作都会产生 NULL。您可以使用 COALESCE(nullable_field, '') || COALESCE(another_nullable_field, '') 满足您的要求。这将合并两个可空字段并返回一个字符串。 - MatBailie

48

1
查询错误:没有这个函数:printf。无法执行语句select printf('%s.%s', id, url ) from mytable limit 7。我的版本是3.8.2 2014-12-06。你使用的是什么版本? - Berry Tsakala
3
3.8.3 中有其他一些小的改进,比如添加了 printf() SQL 函数。 - Sandburg

21

如果您想为连接的行设置自定义字段名称,只需要再加上一行,就像 @tofutim 的答案中所示...

SELECT 
  (
    col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
  ) AS my_column 
FROM
  mytable;

SQLite 3.8.8.3上测试通过,谢谢!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接