如何快速重新索引SQL Server中的列中的值

时间:2019-05-17 17:19:42

标签: python sql-server

我是SQL Sever的新手。现在,我在一列中有值,需要对它进行子字符串处理,然后重新定位这些值。

Ex1: "000000000000000000000000000000" 
  => "000000000000000000000000000000"
Ex2: "168000000000000000000000000000"
  => "168000000000000000000000000000"
Ex3: "192000164000000000000000000000"
  => "192164000000000000000000000000"

示例#1#2是可以的,因为我们什么都不做,但是示例#3很难。

请帮助编写代码到子字符串重新定位值作为输出示例#3

谢谢。

1 个答案:

答案 0 :(得分:0)

由于我不知道您的SQL Server版本,并且您也没有说过要使用哪种语言,因此这里是SQL Server 2017的答案:

--Your Sample Data
WITH VTE AS(
    SELECT V.SomeString
    FROM (VALUES('000000000000000000000000000000'),
                ('168000000000000000000000000000'),
                ('192000164000000000000000000000')) V(SomeString)),
--The Solution
N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP 30 ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) I
    FROM N N1, N N2),
NonZero AS(
    SELECT V.SomeString,
           T.I,
           SS.C
    FROM VTE V
        CROSS JOIN Tally T
        CROSS APPLY (VALUES(SUBSTRING(V.SomeString,T.I,1))) SS(C)
    WHERE SS.C != '0')
SELECT V.SomeString,
       LEFT(CONCAT(STRING_AGG(NZ.C,'') WITHIN GROUP (ORDER BY NZ.I),REPLICATE('0',30)),30) AS NewString
FROM VTE V
     LEFT JOIN NonZero NZ ON V.SomeString = NZ.SomeString
GROUP BY V.SomeString;

db<>fiddle