SQL中的整数值右填充

时间:2017-12-06 05:46:10

标签: sql postgresql

Step1:我有一个名为XYZ的表,其中包含以下整数列:

 ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510

我需要编写一个SQL查询,如果A,B和C的任何值小于8位,那么我需要通过在step2的值右边添加零来将其视为8位数(我不是允许更新表格。)例如:

 ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000

如何通过SQL查询在整数值的右边添加零?

第2步:我需要找到每条记录A<B, B<C。请让我知道如何编写查询。我正在使用PostgreSQL。谢谢。

4 个答案:

答案 0 :(得分:2)

SELECT CAST(2015 AS VARCHAR(10))+REPLICATE('0',8-LEN(2015))

SELECT  2015 *(CAST('1'+REPLICATE('0',8-len(2015))  AS INT))

答案 1 :(得分:1)

试试这个

docker run -it gcr.io/tensorflow/tensorflow:latest-devel

答案 2 :(得分:1)

试试这个:

select cast(left(cast(A as varchar(20)) + '00000000', 8) as int) as [A],
       cast(left(cast(B as varchar(20)) + '00000000', 8) as int) as [B],
       cast(left(cast(C as varchar(20)) + '00000000', 8) as int) as [C]
from TABLE_NAME

如果你想避免任何演员,这可能是解决方案:

select case when 8 - LEN(A) > 0 then A * Power(10, (8 - LEN(A))) else A end as [A],
       case when 8 - LEN(B) > 0 then B * Power(10, (8 - LEN(B))) else B end as [B],
       case when 8 - LEN(C) > 0 then C * Power(10, (8 - LEN(C))) else C end as [C]
from MY_TABLE

答案 3 :(得分:1)

您可以使用rpad()添加尾随零,然后将结果转换回整数:

select id, 
       rpad(a::text, 8, '0')::int, 
       rpad(b::text, 8, '0')::int, 
       rpad(c::text, 8, '0')::int
from the_table;

为避免重复表达式,请使用派生表:

select *
from (
  select id, 
         rpad(a::text, 8, '0')::int as a, 
         rpad(b::text, 8, '0')::int as b, 
         rpad(c::text, 8, '0')::int as c
  from the_table
) t
where a < b or b < c --<< change that to the condition you want