【问题标题】:How to concatenate strings with padding in sqlite如何在sqlite中使用填充连接字符串
【发布时间】:2011-09-02 07:52:04
【问题描述】:

我在一个 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)。我想用- 填充每一列

我是 SQLite 的初学者,任何帮助将不胜感激

【问题讨论】:

标签: string sqlite string-concatenation leading-zero


【解决方案1】:

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

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

对于填充,我使用的看似作弊的方法是从您的目标字符串开始,例如“0000”,连接“0000423”,然后使用 substr(result, -4, 4) 替换“0423”。

更新: 看起来 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"

【讨论】:

  • @Andrew - 通常任何涉及 NULL 的标量操作都会产生 NULL。使用COALESCE(nullable_field, '') || COALESCE(another_nullable_field, '') 可能会满足您的要求。
【解决方案2】:

SQLite has a printf function 正是这样做的:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable

【讨论】:

  • 查询错误:没有这样的功能:printf Unable to execute statement select printf('%s.%s', id, url ) from mytable limit 7. 我的版本是 3.8.2 2014-12- 06.你用的是什么版本?
  • 3.8.3 "还有其他一些小的改进,比如增加了 printf() SQL 函数。"
【解决方案3】:

@tofutim 答案只需多一行...如果您想要连接行的自定义字段名称...

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

SQLite 3.8.8.3 上测试,谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2021-01-31
    • 2013-11-29
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多