简体   繁体   English

SQL 编辑数量字段的查询

[英]SQL Query on editing a quantity field

I have a dataset where the values are different, and I want to bring them into a single format.The values are stored as varchar For ex.我有一个值不同的数据集,我想将它们转换为单一格式。值存储为 varchar For ex。 1st Case: 1.23.45 should be 123.45 2nd Case: 125.45 should be 125.45第一种情况:1.23.45 应为 123.45 第二种情况:125.45 应为 125.45

The first one, has two decimals.第一个,有两位小数。 I want to remove the first decimal only(if there are 2) else let the value be as it is.我只想删除第一个小数点(如果有 2 个),否则让值保持原样。 How do I do this?我该怎么做呢?

I tried using replace(Qty,'.','').我尝试使用 replace(Qty,'.','')。 But this is removing of them.但这是在删除它们。

I think this can do (although I am not 100% sure about corner cases)我认为这可以做到(尽管我对极端情况不是 100% 确定)

SET Qty = SUBSTRING(Qty, 1, LOCATE(Qty, '.') - 1) + SUBSTRING(Qty, LOCATE(Qty, '.') + 1, LENGTH(Qty) - LOCATE(Qty, '.') - 1)
WHERE LENGTH(Qty) - LENGTH(REPLACE(Qty, '.', '')

You can use a regular expression to handle this case.您可以使用正则表达式来处理这种情况。

Assuming there are only two decimals in your string the below query should be able to handle the case.假设您的字符串中只有两位小数,下面的查询应该能够处理这种情况。

select (value,'^(\d+)(\.)?(\d+\.\d+)$',concat('$1','$2')) as a

Here we are matching a regular expression pattern and capturing the following在这里,我们正在匹配一个正则表达式模式并捕获以下内容

  1. digits before first decimal occurrence in group one第一组中第一位小数出现前的数字
  2. digits before and after last decimal occurrence including the last decimal in group two.最后一个小数出现前后的数字,包括第二组中的最后一个小数。

Following that we are concatenating the two captured groups.之后,我们将两个捕获的组连接起来。

Note that the first decimal has been made optional using ?请注意,第一个小数点已使用? character and hence we are able to handle both type of cases.性格,因此我们能够处理这两种情况。

Even if there are more than two decimal cases, I believe a properly constructed regular expression should be able to handle it.即使有两个以上的小数点,我相信一个正确构造的正则表达式应该能够处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM