Trim leading 0 for length greater than x in a dataset

时间:2018-09-28 17:47:41

标签: sql sqlite dataset querying

Take this table for example

Table 1:

Name.  ID
David 00513
George 0523
Carmen 3216

In this table, I want to trim the leading 0 for David only, because his ID is greater than 4 digits. I don't want to trim the leading 0 for George Whats the best way to do this in SQL?

2 个答案:

答案 0 :(得分:2)

最简单的方法是:

select right(id, 4)

如果您担心ID长度超过4个字符但初始字符非零的情况:

select (case when length(id) > 4 
             then replace(ltrim(replace(id, '0', ' ')), ' ', '0')
             else id
        end)

答案 1 :(得分:0)

如果您不担心初始的非零被斩波,那么

select substr(ID,-4);

应该工作。如果有超过4个数字的首字母非零的可能性,请使用

 select printf('%04d', ID);

(假设ID中的所有字符都是数字)