Python 为什么';不能执行sql查询吗?
熊猫为什么不执行sql查询Python 为什么';不能执行sql查询吗?,python,sqlite,pandas,Python,Sqlite,Pandas,熊猫为什么不执行sql查询 import sqlite3 import pandas as pd # load data df = pd.read_csv('CurriculumAuditReport.csv') # strip whitespace from headers df.columns = df.columns.str.strip() con = sqlite3.connect("sans.db") # drop data into database df.to_sql("M
import sqlite3
import pandas as pd
# load data
df = pd.read_csv('CurriculumAuditReport.csv')
# strip whitespace from headers
df.columns = df.columns.str.strip()
con = sqlite3.connect("sans.db")
# drop data into database
df.to_sql("MyTable", con, if_exists='replace')
df = pd.read_sql_query('SELECT Count (Department) FROM MyTable WHERE `CompletedTraining` LIKE 'Incomplete' GROUP BY Department', con)
print(df)
con.close()
该查询在SQLite的DB browser中生成我想要的结果
the output
C:\sans>C:\python34\python test2.py
File "test2.py", line 15
df = pd.read_sql_query('SELECT Count (Department) FROM MyTable WHERE
`CompletedTraining` LIKE 'Incomplete' GROUP BY Department', con)
^
SyntaxError: invalid syntax
我的输出应该有11行您对引用有问题-请尝试以下方法:
df = pd.read_sql_query("SELECT Department, count(*) as cnt FROM MyTable WHERE CompletedTraining = 'Incomplete' GROUP BY Department", con)
您还可以使用以下技术:
qry = """
SELECT department, count(*) as cnt
FROM MyTable
WHERE CompletedTraining = 'Incomplete'
GROUP BY department
"""
df = pd.read_sql_query(qry, con)
您在引用时遇到问题-请尝试以下方法:
df = pd.read_sql_query("SELECT Department, count(*) as cnt FROM MyTable WHERE CompletedTraining = 'Incomplete' GROUP BY Department", con)
您还可以使用以下技术:
qry = """
SELECT department, count(*) as cnt
FROM MyTable
WHERE CompletedTraining = 'Incomplete'
GROUP BY department
"""
df = pd.read_sql_query(qry, con)
首先要提到的是,没有通配符就使用LIKE是没有意义的,只需使用equals即可。或者根据需要添加一个通配符。你想算什么?在你的代码中尝试使用
\'complete\'
,希望能奏效。那么我应该使用什么?\'complete\'可能已经完成了计算,还需要更多的编辑!首先要提到的是,没有通配符就使用LIKE是没有意义的,只需使用equals即可。或者根据需要添加一个通配符。你想算什么?在你的代码中尝试使用\'complete\'
,希望能奏效。那么我应该使用什么?\'complete\'可能已经完成了计算,还需要更多的编辑!谢谢,我能够让它工作,但是使用“不完整的”@DavidBeiler,这是一种在SQL中有点不寻常的计数方式。。。您想统计什么?统计我的表/csv中所有“未完成”的行,但我需要按部门和按部门分组进行统计,这会给出总计数,而不是按部门计数department@davidjbeiler是的,现在它应该显示所有部门(其中CompletedTraining='completed'
)加上相应的行数…谢谢,我能够让它工作,但是使用'complete\'@davidebeiler,这在SQL中是有点不寻常的计数方式。。。您想统计什么?统计我的表/csv中所有“未完成”的行,但我需要按部门和按部门分组进行统计,这会给出总计数,而不是按部门计数department@davidjbeiler是的,现在它应该显示所有部门(其中CompletedTraining='completed'
)连同相应的行数。。。