Cómo concatenar cadenas con relleno en sqlite


Tengo tres columnas en una tabla sqlite:

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

Necesito seleccionar Column1-Column2-Column3 (por ejemplo, A-01-0001). Quiero rellenar cada columna con un -

Soy un principiante con respecto a SQLite, cualquier ayuda sería apreciada

Author: dreftymac, 2011-05-26

3 answers

El operador || es "concatenar" - une las dos cadenas de sus operandos.

De http://www.sqlite.org/lang_expr.html

Para el relleno, la forma aparentemente engañosa que he usado es comenzar con la cadena de destino, digamos '0000', concatenar '0000423', luego substr(result, -4, 4) para '0423'.

Actualización: Parece que no hay implementación nativa de" lpad "o" rpad " en SQLite, pero puede seguir (básicamente lo que propuesto) aquí: 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

Así es como se ve:

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

Rinde

"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"
 316
Author: tofutim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-26 08:22:16

SQLite tiene una función printf que hace exactamente eso:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable
 26
Author: ybungalobill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-01 20:22:27

Solo una línea más para la respuesta @tofutim ... si desea nombre de campo personalizado para la fila concatenada ...

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

Probado en SQLite 3.8.8.3, Gracias!

 12
Author: Madan Sapkota,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-09 03:15:51