如何在Python中使用for循环运行SQL查询。

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

How to use for loop to run sql query in python

问题

  1. import pandas as pd
  2. A = ['A001', 'B001', 'C001', 'Bdd', 'djd.djsx']
  3. AB = pd.DataFrame(A, columns=['app_name'])
  4. # Your SQL query
  5. sql_template = '''
  6. select COUNT(DISTINCT [R_ID])
  7. from database_view
  8. where [app_name] = '{}'
  9. '''
  10. # Create an empty DataFrame to store the final results
  11. final_result = pd.DataFrame(columns=['app_name', 'count'])
  12. # Loop through each app_name in AB
  13. for i in range(len(AB)):
  14. app_name = AB.loc[i, 'app_name']
  15. sql = sql_template.format(app_name)
  16. result = pd.read_sql_query(sql, database)
  17. # Append the result to final_result
  18. final_result = final_result.append({'app_name': app_name, 'count': result.iloc[0, 0]}, ignore_index=True)
  19. final_result

This code should execute your SQL query for each app_name in the AB DataFrame, and append the results to the final_result DataFrame in the format you expect.

英文:

I have 100 records in table A, I only list 4 here but please use loop to solve this question

  1. A = ['A001', 'B001','C001','Bdd','djd.djsx']
  2. AB = pd.DataFrame(A, columns = ['app_name'])
  3. AB
  4. app_name
  5. 0 A001
  6. 1 B001
  7. 2 C001
  8. 3 Bdd
  9. 4 djd.djsx

I have SQL query looks like this

  1. select COUNT (DISTINCT [R_ID])
  2. from database_view
  3. where [app_name] in ('A001')

I want to use loop to execute the query for 100 times and append the final result to the AB

What I tried is:

  1. For i in AB:
  2. sql = '''select COUNT (DISTINCT [R_ID])
  3. from database_view
  4. where [app_name] in {i}'''
  5. a=pd.read_sql_query(sql,database)
  6. final = AB.append(a,ignore_index = True)
  7. final

but it does not work, and also I find it will add one more column to the right of df"AB", but it will append the count number to a new row at last.

Expected Result looks likes this,
expected result

it means for app A001, it has 6 different R_ID,
for app B001 it has 1 different R_ID

Any help is really appreicated!

答案1

得分: 1

考虑一个单一的聚合查询,使用GROUP BY,无需任何for循环,并且无需追加到数据框中。一旦SQL查询运行,使用DataFrame.query来筛选结果到你的100个应用程序列表中。

  1. sql = '''SELECT [app_name], COUNT(DISTINCT [R_ID]) AS r_id_count
  2. FROM database_view
  3. GROUP BY [app_name]
  4. '''
  5. apps = AB["app_name"].tolist()
  6. app_counts_df = (
  7. pd.read_sql_query(sql, database)
  8. .query("app_name == @apps")
  9. )
英文:

Consider a single aggregate query using GROUP BY without any for-loop and the need to append to data frame. Once SQL query runs, filter result with DataFrame.query to your list of 100 apps.

  1. sql = '''SELECT [app_name], COUNT(DISTINCT [R_ID]) AS r_id_count
  2. FROM database_view
  3. GROUP BY [app_name]
  4. '''
  5. apps = AB["app_name"].tolist()
  6. app_counts_df = (
  7. pd.read_sql_query(sql, database)
  8. .query("app_name == @apps")
  9. )

答案2

得分: 0

你忘记在 for 循环和 SQL 查询的 f-string 中加入列名。尝试使用以下代码:

  1. for i in AB['app_name']:
  2. sql = f'''select COUNT (DISTINCT [R_ID])
  3. from database_view
  4. where [app_name] in {i}'''

更新-1:编辑 SQL 查询:

  1. # 创建一个空的数据框:
  2. df = pd.DataFrame()
  3. for i in AB['app_name']:
  4. sql = f'''select app_name, COUNT (DISTINCT [R_ID])
  5. from database_view
  6. where [app_name] in {i}
  7. GROUP BY app_name'''
  8. a = pd.read_sql_query(sql, database)
  9. final = df.append(a, ignore_index=True)
  10. print(final)
英文:

You forgot to put column name in for loop and f-string in SQL query. Try this code:

  1. for i in AB['app_name']:
  2. sql = f'''select COUNT (DISTINCT [R_ID])
  3. from database_view
  4. where [app_name] in {i}'''

Update-1: Edit SQL query:

  1. # Create an empty dataframe:
  2. df=pd.DataFrame()
  3. for i in AB['app_name']:
  4. sql = f'''select app_name,COUNT (DISTINCT [R_ID])
  5. from database_view
  6. where [app_name] in {i}
  7. GROUP BY app_name'''
  8. a=pd.read_sql_query(sql,database)
  9. final = df.append(a,ignore_index = True)
  10. print(final)

huangapple
  • 本文由 发表于 2023年6月9日 02:59:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434943.html
匿名

发表评论

匿名网友

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

确定