将数据类型nvarchar转换为int并除

时间:2018-10-25 10:46:41

标签: sql sql-server type-conversion

我正在使用SQL Server 2016,并且我有一个包含2列且数据类型为nvarchar的表 第一列'100〜50'和第二列'50〜25'中的数据 我想将第一列划分为第二列,最终数据为“ 2〜2”

3 个答案:

答案 0 :(得分:2)

好您应该真正修复数据结构,因此单个列没有多个值。以下是除法-计算组成部分:

select cast(v1.col1_1 as int) / cast(v2.col2_1 as int) as new_col1,
       cast(v1.col2_2 as int) / cast(v2.col2_2 as int) as new_col2      
from t cross apply
     (values (left(t.col1, charindex('~', t.col1) - 1),
              left(t.col1, charindex('~', t.col2) - 1)
             )
     ) v1(col1_1, col2_1) cross apply
     (values (stuff(t1.col1, 1, len(v1.col1_1) + 1, ''),
              stuff(t2.col1, 1, len(v1.col2_1) + 1, '')
             )
     ) v2(col1_2, col2_2);

正如我之前所说,多个值不应存储在单个字符串中,因此,我不建议您将其放回字符串中。

答案 1 :(得分:1)

您可以:

sample_df
      id                date happy      type
1   1912 2018-10-08 11:32:55     0      blue
2   1912 2018-10-05 11:32:55     0       red
3   1912 2018-10-08 09:09:56     0       red
4   1912 2018-10-05 11:32:55     0   tuesday
7   2191 2018-10-15 08:17:47     0       red
8   2191 2018-09-29 10:16:34     0     green
9   2191 2018-07-09 18:28:25     0      blue
10  2191 2018-07-09 18:28:25     0     green
15  2192 2018-07-09 18:20:32     0    purple
16  2192 2018-08-30 13:06:45     0      blue
17  2192 2018-07-09 18:28:25     0    monday
19 14129 2018-06-15 00:15:42     0      blue
20 14129 2018-10-08 12:44:44     0      blue
21 14129 2018-07-09 18:14:58     0     green
22 14129 2018-06-15 00:15:42     1    monday
25 29102 2018-06-15 00:15:40     0       red
26 29102 2018-06-15 00:19:42     0       red
27 29102 2018-06-15 00:15:40     1 wednesday

编辑:您可以使用select concat(cast(left(col1, charindex('~', col1) - 1) as int) / cast(right(col1, len(col1) - charindex('~', col1)) as int), '~', cast(left(col2, charindex('~', col2) - 1) as int) / cast(right(col2, len(col2) - charindex('~', col2)) as int) ) from table t; 子句来避免算术错误divide by zero

where

答案 2 :(得分:0)

您可以在下面尝试

DEMO

 select concat(val1,'~',val2) as col
from
(
select cast(substring(column1,0,charindex('~',column1)) as int)/cast(substring(column2,0,charindex('~',column2)) as int) as val1,
cast(substring(column1,charindex('~',column1)+1,len(column1)-charindex('~',column1)) as int)/cast(substring(column2,charindex('~',column2)+1,len(column2)-charindex('~',column2)) as int) as val2
from cte1
)X

输出:

col
2~2