如何根据mysql中字符串的长度修剪前导零

时间:2015-10-20 13:15:12

标签: mysql case trim

我的表中有一个名为UPC的列。该列允许最多13位。例如,列值应该是这样的。

0892902000161
0097512135764
4046228003979

现在我需要修剪一个零,如果它有前导两个零,如0097512135764.现在我使用下面的查询来修剪所有前导零。

SELECT TRIM(LEADING '0' FROM `UPC`) upc FROM `mytable`.

但是现在我需要修剪一个零,如果它有两个前导零。有一个可以指导我。任何帮助将不胜感激。

SELECT 
  CASE WHEN UPC LIKE '00%' THEN RIGHT(UPC, LENGTH(UPC) -1)
  ELSE UPC
  END AS UPC
FROM `mytable`

in the same query how can we check the count of upc number? I mean if length of upc is 13 
digits and first one is zero then need to remove first zero. Then upc length should be 12. 
If upc length is 13 and first two are zeros then need to remove single zero. 
Then also upc length should be 12 digits.How can we acheive this?

1 个答案:

答案 0 :(得分:1)

CASE就足够了。以UPC开头的00...获取UPC而没有第一个字符。

SELECT 
  CASE WHEN UPC LIKE '00%' THEN RIGHT(UPC, LENGTH(UPC) -1)
  ELSE UPC
  END AS UPC
FROM `mytable`

LiveDemo

修改

  

如果upc长度为13,前两个为零,则需要删除   单零。

     

如果upc的长度为13位且第一个为零,那么需要   删除第一个零。

SELECT 
  CASE 
   WHEN UPC LIKE '00%' AND LENGTH(UPC) = 13 THEN RIGHT(UPC, LENGTH(UPC) -1)
   WHEN UPC LIKE '0%' AND LENGTH(UPC) = 13 THEN RIGHT(UPC, LENGTH(UPC) -1)
  ELSE UPC
  END AS UPC
FROM `mytable`

LiveDemo