232

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

4

3 回答 3

411

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

来自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 功能/

-- 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"
于 2011-05-26T06:17:54.897 回答
44

SQLite 有一个printf功能可以做到这一点:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable
于 2014-09-01T20:22:27.523 回答
18

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

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

SQLite 3.8.8.3上测试,谢谢!

于 2015-04-09T03:15:51.577 回答