SQLite 3.6.21:使用唯一列值“挤压”出NULL值

时间:2015-07-17 18:00:50

标签: sqlite

使用SQLite 3.6.21,我想更新表中的列。

如果该列中只有1个唯一的实际值,则目标是从列中“挤出”NULL。如果LastName包含“Smith”,“Johnson”和NULL,则不执行任何操作。

例如:

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);

由于只有一个姓氏,我想用Smith替换NULL。我试过这个没有成功。它最终用NULL替换整个列。

UPDATE foo
SET LastName = 
    ( CASE
         WHEN ((select count(distinct LastName) from foo) = 1)  THEN (SELECT distinct LastName from foo)
         ELSE LastName
      END
    );

编辑:

我正在使用以下代码在Python中执行此操作:

import sqlite3 as lite

'''
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

1 个答案:

答案 0 :(得分:1)

Python重新排序" SELECT不同的LastName来自foo"所以NULL是第一个值。 SQL提供了#34; Smith"作为第一个值。要忽略NULL,我将该行更改为

...THEN (SELECT distinct LastName from foo where LastName is NOT NULL)

编辑:

从SQL控制台复制:

sqlite>
sqlite> SELECT distinct LastName from foo;
Smith

sqlite>

从Python复制:

with con:
    cur = con.cursor()
    cur.execute("SELECT distinct LastName from foo")
    answer = cur.fetchall()
    print answer

结果

[(None,), (u'Smith',)]