如何拆分出现两次的字符串?

时间:2016-07-13 10:16:45

标签: sql sql-server

我有一个表名为NAME的表格,以及如下数据:

NAME
-------------
sumansuman
nehaneha
anjalianjali

我想这样输出:

NAME
-------------
suman 
neha
anjali

4 个答案:

答案 0 :(得分:5)

如果您确定每个名称都完全重复,那么这应该有效

SELECT LEFT(name, LEN(name)/2) FROM temp

要捕捉不是这种情况的行:

SELECT name FROM temp
WHERE NOT name = LEFT(name, LEN(name)/2) + LEFT(name, LEN(name)/2)

答案 1 :(得分:1)

尝试这样的事情,

DECLARE @MyTable TABLE(NAME VARCHAR(100))

INSERT INTO @MyTable
VALUES
     ('sumansuman')
    ,('nehaneha')
    ,('anjalianjali')
    ,('suman')
    ,('nehaanjali')

SELECT CASE WHEN SUBSTRING(NAME,1,len(NAME)/2) = SUBSTRING(NAME,(len(NAME)/2)+1,len(NAME)) 
                THEN SUBSTRING(NAME,1,len(NAME)/2) 
            ELSE NAME
        END
FROM @MyTable

结果是:

Output
------
suman
neha
anjali
suman
nehaanjali

答案 2 :(得分:1)

使用CTE使查询更有效(每行只执行一次LEFT和LEN)并且更具可读性:

with CTE as (
    select name, LEFT(name, LEN(name)/2) half from temp
)
select case name when half + half then half
  else name end as name
from CTE

如果您只想 ,请修改双重名称:

with CTE as (
    select name, LEFT(name, LEN(name)/2) half from temp
)
select half as name
from CTE
where name + half + half

答案 3 :(得分:0)

您可以使用& 正确功能使逻辑可读:

DECLARE @MyTable TABLE(NAME VARCHAR(100))

INSERT INTO @MyTable
VALUES
     ('sumansuman')
    ,('nehaneha')
    ,('anjalianjali')
    ,('suman')
    ,('nehaanjali')

SELECT  Case 
        when Left(NAME,len(NAME)/2) = Right(NAME,len(NAME)/2)
        then Left(NAME,len(NAME)/2) 
        else NAME 
        end
FROM @MyTable