I need help understanding why a sql command works on the command line however it doesn't work when executed from python 2.7.
The goal is to "squeeze" out NULLs from a column if there is only 1 unique real value in that column. For example:
In SQL:
create table foo (FirstName char(20), LastName char(20));
insert into foo values ('Joe', 'Smith');
insert into foo values ('Susan', NULL);
insert into foo values ('Shirley', 'Smith');
insert into foo values ('Kevin', NULL);
Since there is only one last name, I want to replace the NULLs with Smith. This works on the command line.
UPDATE foo
SET LastName =
( CASE
WHEN ((select count(distinct LastName) from foo) = 1) THEN (SELECT distinct LastName from foo)
ELSE LastName
END
);
In Python:
con = lite.connect('test.db')
names = (
('Joe', 'Smith'),
('Susan', None),
('Shirley', 'Smith'),
('Kevin', None),
)
squeezecmd = '''UPDATE foo SET LastName = (CASE
WHEN ((select count(distinct LastName) from foo) = 1)
THEN (SELECT distinct LastName from foo) ELSE LastName END);'''
with con:
cur = con.cursor()
cur.execute("CREATE TABLE foo(FirstName TEXT, LastName TEXT)")
cur.executemany("INSERT INTO foo VALUES(?, ?)", names)
cur.execute(squeezecmd)
cur.execute("SELECT * FROM foo")
rows = cur.fetchall()
for row in rows:
print row
This results in replacing every value in LastName with None (or NULL). I think it's because distinct(LastName) results in a list instead of a single value like on the command line but I'm not sure.
Any ideas?
EDIT:
So SELECT distinct LastName from foo
results in 1 answer in SQL but 2 answers in Python. SQL responds with "Smith" while Python gives [None, u"Smith"]
. Any way to make the python distinct ignore the NULLs?
Aucun commentaire:
Enregistrer un commentaire