I am trying to build a SQL that needs to be filtered by two parameters (2 columns), and the second column needs to match multiple values.
Given below is the SQL I have build thus far (thanks for the help of Martijn Pieters)
import psycopg2
import pandas as pd
import datetime
# Connecting to db
con = psycopg2.connect(db_details)
cur = con.cursor()
cur.execute("select * from sales limit 10")
rows = cur.fetchall()
params = {'earliest': datetime.datetime.today() - datetime.timedelta(days=7),
'store_name': 'store_1', 'store_2'}
df = pd.read_sql("""
select store_name,count(*) from sales
where created_at >= %(earliest)s
and store_name = %(store_name)s""",
params=params, con=con)
The above SQL has one date parameter which is used in the where clause and I added one more parameter namely the store_name, where rows match either one of two values.
Would like to know how could I add in this additional parameter to the existing query.
I tried to create a the parameter (similar to the date filter) and pass that to the existing query but get a syntax error when I give it two values:
'store_name': 'store_1', 'store_2'}
^
SyntaxError: invalid syntax
pointing to the params field.
store_name = ...for a single value, you'd have to usestore_name in (<value1>, <value2>, ..., <valueN>). I was hoping your question would really just focus on that latter problem.store_nameat least people trying to answer your question will see this is acolumnname IN (value, value, value)test, not a straight single-valuecolumnname = valuetest. A SQLINtest with parameters requires extra work from the Python programmer because now you have to generate SQL text for those parameters.'store_name': 'store_1'(so a single string value), the code would have worked as is. So the real problem here is not defining parameters, it is defining parameters with more than one value.