我有以下 SQL 查询,并希望使用sqlparse
import sqlparse
query = """
select SUM(case when(A.dt_unix<=86400
and B.flag="V") then 1
end) as TEST_COLUMN_1,
SUM(case when(A.Amt - B.Amt > 0
and B.Cat1 = "A"
and (B.Cat2 = "M"
or B.Cat3 = "C"
or B.Cat4 = "B")
and B.Cat5 is NULL) then 1
end) as TEST_COLUMN_2
from test_table A
left join test_table_2 as B on A.ID=B.ID
where A.DT >B.DT
group by A.ID
"""
query_tokens = sqlparse.parse(query)[0].tokens
print(query_tokens)
将给出 SQL 语句中包含的所有标记:
[<Newline ' ' at 0x7FAA62BD9F48>, <DML 'select' at 0x7FAA62BE7288>, <Whitespace ' ' at 0x7FAA62BE72E8>, <IdentifierList 'SUM(ca...' at 0x7FAA62BF7CF0>, <Newline ' ' at 0x7FAA62BF6288>, <Keyword 'from' at 0x7FAA62BF62E8>, <Whitespace ' ' at 0x7FAA62BF6348>, <Identifier 'test_t...' at 0x7FAA62BF7570>, <Newline ' ' at 0x7FAA62BF64C8>, <Keyword 'left j...' at 0x7FAA62BF6528>, <Whitespace ' ' at 0x7FAA62BF6588>, <Identifier 'test_t...' at 0x7FAA62BF7660>, <Whitespace ' ' at 0x7FAA62BF67C8>, <Keyword 'on' at 0x7FAA62BF6828>, <Whitespace ' ' at 0x7FAA62BF6888>, <Comparison 'A.ID=B...' at 0x7FAA62BF7B10>, <Newline ' ' at 0x7FAA62BF6B88>, <Where 'where ...' at 0x7FAA62BF28B8>, <Keyword 'group' at 0x7FAA62BD9E88>, <Whitespace ' ' at 0x7FAA62BD93A8>, <Keyword 'by' at 0x7FAA62BD9EE8>, <Whitespace ' ' at 0x7FAA62C1CEE8>, <Identifier 'A.ID' at 0x7FAA62BF2F48>, <Newline ' ' at 0x7FAA62BF6C48>]
如何解析这些标记,以便以CASE WHEN
一种可以提取所有条件并保持它们的优先级的方式处理语句,如使用括号定义的那样。我无法在文档中找到任何相关示例。
对此有什么想法吗?