【问题标题】:SQL break into 3 columnsSQL分成3列
【发布时间】:2020-04-03 18:34:20
【问题描述】:

我有一个名为“stuff”的字段名称
还有一些这样的记录

info,caow~13909~182029~10593~H7Q0B7MM
info,caow~4964~152073~16863~MF4B8MBC
info,caow~590~265~517~H7Q0B7MM

我的目标是像这样分成 3 列

columnA   ColumnB   ColumnC
13909     182029    10593
4964      152073    16863
590       265       517

请您帮忙。谢谢你。

【问题讨论】:

  • 你在乎订单是什么
  • 不需要订单号

标签: sql sql-server


【解决方案1】:

使用一点 XML 的另一种选择

示例

Select B.*
 From  YourTable A
 Cross Apply (
                Select Pos2 = xDim.value('/x[2]','varchar(max)')
                      ,Pos3 = xDim.value('/x[3]','varchar(max)')
                      ,Pos4 = xDim.value('/x[4]','varchar(max)')
                From  ( values (cast('<x>' + replace((Select replace(SomeCol,'~','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml)))  A(xDim)
             ) B

退货

Pos2    Pos3    Pos4
13909   182029  10593
4964    152073  16863
590     265     517

编辑 - 稍薄的版本

Select B.*
 From  YourTable A
 Cross Apply (
                Select Pos2 = xDim.value('/x[2]','varchar(50)')
                      ,Pos3 = xDim.value('/x[3]','varchar(50)')
                      ,Pos4 = xDim.value('/x[4]','varchar(50)')
                From  ( values (cast('<x>' + replace(SomeCol,'~','</x><x>')+'</x>' as xml)))  A(xDim)
             ) B

【讨论】:

  • 我有 50000 条这样的记录。
  • @ngoc 需要明确的是,(at)YourTable 只是一个演示表变量。表演真的很不错。从您的实际表中尝试前 5000 条记录
  • @ngoc 性能可以稍微调整一下,如果你可以 gtd XML 安全字符
  • @ngoc 请参阅“更薄”版本的编辑。前提是您有 XML 安全字符
  • @ngoc 很好奇,两者都对我有用。我很少在没有先测试的情况下发布代码:)
【解决方案2】:

如果你不关心排序,你可以使用:

select s.*
from t cross apply
     (select max(case when seqnum = 1 then value end) as value1,
             max(case when seqnum = 2 then value end) as value2,
             max(case when seqnum = 3 then value end) as value3
      from (select s.value,
                   row_number() over (order by (select null)) as seqnum
            from string_split(t.col, '~') s
            where s.value not like '%[^0-9]%'
           )
    ) s;

其实,如果你没有重复,你可以使用:

row_number() over (order by (select charindex(s.value, t.col)) as seqnum

对于seqnum 的定义。

【讨论】:

  • 使用您的查询有点困惑。如果我的查询像这样从 GetDetail 中选择内容,那么我将如何匹配您的查询。谢谢
  • select s.* from t cross apply (select max(case when seqnum = 1 then value end) as value1, max(case when seqnum = 2 then value end) as value2, max(case when seqnum = 3 then value end) as value3 from (select s.stuff, row_number() over (order by (select null)) as seqnum from GetDetails(t.col, '~') s where s.varstring not like '% [^0-9]%' ) ) s;然后在')'附近出现错误语法错误。
猜你喜欢
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2012-01-31
  • 2014-07-24
  • 2011-12-07
  • 2021-08-23
  • 2017-10-04
  • 1970-01-01
相关资源
最近更新 更多