代码示例:
import sqlalchemy as sa
# 自定义列表
rows = [('BTC_USD', '0_4', 1),
('BTC_USD', '4_8', 2),
('BTC_USD', '8_12', 4),
('BCH_USD', '0_4', 10),
('BCH_USD', '4_8', 8),
('BCH_USD', '8_12', 6),
('LTC_USD', '0_4', 7),
('LTC_USD', '4_8', 8),
('LTC_USD', '8_12', 9)
]
stmts = [
# @NOTE: optimization to reduce the size of the statement:
# make type cast only for first row, for other rows DB engine will infer
sa.select([
sa.cast(sa.literal(i), sa.String).label("symbol"),
sa.cast(sa.literal(v), sa.String).label("duration"),
sa.cast(sa.literal(d), sa.Integer).label("rate"),
]) if idx == 0 else
sa.select([sa.literal(i), sa.literal(v), sa.literal(d)]) # no type cast
for idx, (i, v, d) in enumerate(rows)
]
subquery = sa.union_all(*stmts)
print(subquery)
# Choose one option below.
# I personally prefer B because one could reuse the CTE multiple times in the same query
subquery = subquery.cte(name="temp_table")
print(subquery.c.duration)