首页 > 解决方案 > 将单个 sql 列拆分为五个

问题描述

我试图在“ >”分隔符周围将一列分成最多五列,但我尝试过的事情没有得到解决:

我试过

select
id, 
compoundColumn,
split(compoundColumn," > ")[1] as "first"
split(compoundColumn," > ")[2] as "second"
from table
where compoundColumn is not null

这没有用,并且

这是哪一种(无论如何是第一部分,而不是第n部分)

select
id, 
compoundColumn,
first(split(compoundColumn," > ")) as "first"
nth(compoundColumn," > ")[n] as "second"
from table

我在这里找到了很多示例,但它们似乎都在说要使用括号,但括号会引发错误:

例外:格式错误的 SQL。更多信息: SQL 语句错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 3 行使用 '[1] 作为表中的“第一个”,其中复合列不为 NULL'。

标签: sqlgoogle-cloud-sqllegacy-sql

解决方案


  • SQL 中的“first”之后缺少逗号
  • 我猜 CloudSQL 是基于一些旧版本的 MySQL,它只能使用 substring_index 进行拆分(请参阅下面的查询 - 是的,它冗长而笨拙,case 子句必须清理短字符串)
  • 也许尝试使用[offset(0)]or的括号[ordinal(1)],这对我们有用,尽管我们使用 Postgres 方言,也作为#standardSql,而不是#legacySql

第二点的SQL:(小提琴

select id,
  case when substring_index(cc,' > ',0) = cc then null else substring_index(substring_index(cc,' > ',1),' > ',-1) end as a1,
  case when substring_index(cc,' > ',1) = cc then null else substring_index(substring_index(cc,' > ',2),' > ',-1) end as a2,
  case when substring_index(cc,' > ',2) = cc then null else substring_index(substring_index(cc,' > ',3),' > ',-1) end as a3,
  case when substring_index(cc,' > ',3) = cc then null else substring_index(substring_index(cc,' > ',4),' > ',-1) end as a4,
  case when substring_index(cc,' > ',4) = cc then null else substring_index(substring_index(cc,' > ',5),' > ',-1) end as a5
from d

推荐阅读