假设我有下面的string
,其中包含从SELECT
子句中提取的SQL语句(实际上,这是一个包含数百个这样的语句的巨大SQL语句)
SUM(case when(A.money-B.money>1000
and A.unixtime-B.unixtime<=890769
and B.col10 = "A"
and B.col11 = "12"
and B.col12 = "V") then 10
end) as finalCond0,
MAX(case when(A.money-B.money<0
and A.unixtime-B.unixtime<=6786000
and B.cond1 = "A"
and B.cond2 = "4321"
and B.cond3 in ("E", "F", "G")) then A.col10
end) as finalCond1,
SUM(case when(A.money-B.money>0
and A.unixtime-B.unixtime<=6786000
and B.cond1 = "A"
and B.cond2 = "1234"
and B.cond3 in ("A", "B", "C")) then 2
end) as finalCond2
如何在函数(即SUM
、MAX
、MIN
、MEAN
等)上拆分此查询,以便在不删除分隔符的情况下提取最后一个查询(在本例中是SUM
)?在
因此,所需的输出将是一个如下所示的字符串:
^{pr2}$PS:出于表示目的,我提供了一些缩进,但实际上这些语句是用逗号分隔的,这意味着原始格式中没有空白或新行。在
在这里不能使用正则表达式,因为SQL语法不形成可以与Python
re
引擎匹配的正则模式。实际上,您必须将字符串解析为令牌流或语法树;毕竟,SUM(...)
可以包含大量语法,包括子选择。在^{} library 可以这样做,即使它是bit underdocumented and not that friendly to external uses。在
重新使用我在链接到的另一篇文章中定义的
walk_tokens
函数:从
^{pr2}$SELECT
标识符列表中提取最后一个元素是:演示:
identifier
是一个sqlparse.sql.Identifier
实例,但是再次将其转换为字符串(这是print()
所做的,或者您可以只使用str()
)为该部分再次提供输入SQL字符串。在您可以使用类似于:
在
^{pr2}$commas
数组中,将有需要拆分的逗号。输出将是:在parts中,您将拥有包含这些部分的最终数组(不确定此实现是否是最佳方法):
我有一个解决方案,但代码有点多。这没有使用
regex
,只是对关键字进行多次拆分。在我得到的输出是:
^{pr2}$对你有用吗?它似乎适用于你在问题中输入的示例字符串。在
相关问题 更多 >
编程相关推荐