Sql查询将一列拆分为两列 [英] Sql query to split one column into two columns

查看:59
本文介绍了Sql查询将一列拆分为两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单列作为项目名称,其中的数据项目名称

I have one single column as project name, the data in project name

1.1.1 chapter1
1.1.2 chapter2

我想将该单列分成两列

Major   Minor
1.1     .1 chapter1
1.1     .2 chapter2

我的项目名称列的数据类型是 nvarchar,我正在使用 sql 2005

the datatype of my project name column is nvarchar, I am using sql 2005

有什么帮助吗?

推荐答案

类似这样的事情

declare @x nvarchar(500) = '1.1.1 chapter1'

select substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1) as Major,
       substring(@x,charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x))) as Minor

在您的查询中替换@x ..

Substitute @x in your query ..

和它的小提琴:http://sqlfiddle.com/#!3/d41d8/4424/0

更新为 .在前面和证明错误

updated with the . in front and proof to error

声明@x nvarchar(500) = '1.1.1 Chapter1'

declare @x nvarchar(500) = '1.1.1 chapter1'

select @x,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1)
        else 'Cannot be parsed'
   end,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x))+1)
        else 'Cannot be parsed'
   end

并且没有 .前面

声明@x nvarchar(500) = '1.1.1 Chapter1'

declare @x nvarchar(500) = '1.1.1 chapter1'

select @x,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1,charindex('.',@x,1+charindex('.',@x))-1)
        else 'Cannot be parsed'
   end,
   case when charindex('.',@x,1+charindex('.',@x)) <> 0 then substring(@x,1+charindex('.',@x,1+charindex('.',@x)),len(@x)-charindex('.',@x,1+charindex('.',@x)))
        else 'Cannot be parsed'
   end

http://sqlfiddle.com/#!3/d41d8/4430/0

这篇关于Sql查询将一列拆分为两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆