简体   繁体   中英

Using SQL Cases with Pandas pd.read_sql?

I am using pandas pd.real_sql(SQL Query, con) to read in data from a database. When I use a basic query like SELECT * FROM COLUMN WHERE ROW IS NOT NULL I get a normal result. But, I can't figure out how to use cases. When I try to use a case I always get an error ...near "CASE": syntax error

SELECT * CASE WHEN Column IS NULL THEN False ELSE True END AS TrueFalse FROM Sheet",con Anyone know how to use sql cases with pandas

import psycopg2 as pg
import pandas.io.sql as psql
import pandas as pd

Q1 = '''
select col1, col2,
case when col1 is null THEN '1' ELSE '0' END AS col3
from table1
'''

connection = pg.connect("host='ABC' dbname=ABC user=ABC 
password='ABC'")

df = pd.read_sql_query(Q1, con=connection)

*replace ABC with your db host name, db name, user name and password

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM