sql - 将单个 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'。
解决方案
- 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
推荐阅读
- python - 训练这个模型会导致内存泄漏
- python - 如何检查子集是否包含在列表中?
- java - 无法获取加入延迟初始化的集合
- lua - 为什么下面的代码没有给出任何结果?
- r - 映射和left_joining 两个列表在一起
- servicestack - ServiceStack - 在请求过滤器之前调用 [Authenticate] 属性。不适用于 OrmLiteMultitenancyAuthRepository / OrmLiteCacheClient
- android - 如何在画布中的弧线笔划上应用radialGradient
- sql-server - 如何在不使用循环的情况下更新 SQL Server 中两组不同条件之间的行
- android - 从活动到片段的共享偏好
- python - 如何修复 matplotlib y 轴数不一致