【问题标题】:Converting varchars into two points Decimal value by using SQL使用 SQL 将 varchar 转换为两点十进制值
【发布时间】:2013-10-10 22:41:03
【问题描述】:

我有一个包含以下金额列表的平面文件,请您告诉我,我怎样才能将下面的金额列表转换为以 {,A,H,E,C 结尾的 1234567.80 之类的两位十进制值,I,F 使用 SQL 吗?

12345678{
00484326A
00000210H
00000185A
00000077E
00000833C
00000255I
00000077E
00000039F
00000088A
00000000F
00000000A
00000100{  

谢谢,

【问题讨论】:

  • 目前无法为您编写,但请尝试使用 SUBSTRING 和 CASE。
  • 我可以做子字符串,但我必须知道,为什么每个值都以特定字符结尾。我认为有理由知道。
  • eequalsmcaputo 给了你 CASE 部分。

标签: mysql sql decimal sql-function


【解决方案1】:

试试with this SQLfiddle。不漂亮,但很管用

SELECT 
    CAST(
        CONCAT(SUBSTRING(test_value,1, LENGTH(test_value) -2),
               '.',
               SUBSTRING(test_value, LENGTH(test_value) -1, 1))
    AS DECIMAL(7,1))
FROM TEST
WHERE SUBSTRING(test_value, LENGTH(test_value)) = 'A' 
|| SUBSTRING(test_value, LENGTH(test_value)) = 'H'
-- keep adding above line for the rest of the ending characters you want

【讨论】:

    【解决方案2】:

    我把它写成一个函数是因为我认为它比内联代码更容易阅读:

    create function dbo.convert_amount_str ( @amount_str varchar(50) )
    returns money
    as
    begin
    declare @char_index int
    declare @amount money
    declare @char varchar(50)
    declare @decimal money
    
    -- Match the first non-numeric character
    select @char_index = PATINDEX('%[^0-9]%', @amount_str)
    
    -- Get the numeric characters into a numeric variable
    select @amount = convert(money, SUBSTRING(@amount_str, 0, @char_index))
    
    -- Get the non-numeric character (will work for multiple characters)
    select @char = SUBSTRING(@amount_str, @char_index, (len(@amount_str) - @char_index) + 1)
    
    -- Convert the non-numeric characters into decimal amounts
    select @decimal = case @char
        when 'A' then .8 -- whatever this should equate to
        when 'H' then .7 -- whatever this should equate to
        -- output for remaining characters
        end
    
    return @amount + @decimal
    end
    

    然后像这样使用它:

    select dbo.convert_amount_str('00484326A')
    

    或者,更可能的是,引用包含数字字符串值的任何列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2013-04-18
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多