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

时间:2011-05-26 06:11:52

标签: string sqlite string-concatenation leading-zero

我在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的初学者,任何帮助都将不胜感激

3 个答案:

答案 0 :(得分:352)

  

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

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

对于填充,我使用的看似骗子的方式是从你的目标字符串开始,比如'0000',连接'0000423',然后是'0423'的substr(结果,-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"

答案 1 :(得分:31)

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

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

答案 2 :(得分:15)

@tofutim的答案还有一行...如果你想为连续行自定义字段名...

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

SQLite 3.8.8.3上测试,谢谢!

相关问题