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

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

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

问题

下面是用于从表中生成计数的函数,但在查询(字符串)中,我想要添加“group by”一个列“xyz”。建议如何执行相同的操作。
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.

from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession
from pyspark.sql.types import *

db = 'database'
schema = 'Schema'

def getCount(table):
    string = f"select count(*) as ct from {db}.{schema}." + table
    df = spark.read.format(snowflake_name)\
                         .options(**sfOptions)\
                         .option('query', string).load()
    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

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:

确定