如何扩展查询,如果 SQL 查询是带参数的?

huangapple go评论84阅读模式
英文:

How to extend the query if the sql query is parametrized?

问题

  1. 下面是用于从表中生成计数的函数,但在查询(字符串)中,我想要添加“group by”一个列“xyz”。建议如何执行相同的操作。
  1. string = f"select count(*) as ct from {db}.{schema}." + table + " group by xyz"
英文:

Below is the function created to generate counts from the table, but in the query (string) I want to add 'group by' a column 'xyz'. Suggest, how to do the same.

  1. from pyspark import SparkContext, SparkConf
  2. from pyspark.sql import HiveContext
  3. from pyspark.sql import SQLContext
  4. from pyspark.sql import SparkSession
  5. from pyspark.sql.types import *
  6. db = 'database'
  7. schema = 'Schema'
  8. def getCount(table):
  9. string = f"select count(*) as ct from {db}.{schema}." + table
  10. df = spark.read.format(snowflake_name)\
  11. .options(**sfOptions)\
  12. .option('query', string).load()
  13. return df

答案1

得分: 0

string = f"更改f字符串的一种方式是:\n\npy\nstring = f\"选择 some_column,计数(*) 作为 ct 从 {db}.{schema}.{table} 按 some_column 分组\"\n"

英文:

Well one way would be to alter the f-string slightly

  1. string = f"select some_column, count(*) as ct from {db}.{schema}.{table} group by some_column"

huangapple
  • 本文由 发表于 2023年2月16日 13:00:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定