在 python 中使用 sqlite3 计算跨列的不同值

问题描述 投票:0回答:4

我正在尝试在 python 中使用 sqlite3 计算跨列的不同值,但似乎无法获得正确的结果。我只能获得 1 列中不同值的计数。

我已经创建了一个数据库并将 csv 文件导入为一个表

conn = sqlite3.connect('test.db')
curr = conn.cursor()

curr.execute('DROP TABLE IF EXISTS test')
curr.execute('CREATE TABLE social_table (from_id INTEGER, to_id INTEGER)')
conn.commit()

with open ('test.csv') as f:
    reader = csv.reader(f)
    next(reader, None)

    for row in reader:
        from_id = row[0]
        to_id = row[1]

        curr.execute('INSERT INTO test (from_id, to_id) VALUES (?, ?)',
                    (from_id, to_id))
    conn.commit()
来自_id to_id
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 10
0 11

此表中跨列的唯一用户应该是 11 但我的代码

curr.execute("Select Count(*) from (Select DISTINCT from_id, to_id from test)")

给我 10 个。

有人能帮我吗?

python sql sqlite count distinct
4个回答
0
投票

看来你的查询不正确,试试这个:

curr.execute("""
    SELECT COUNT(DISTINCT user_id) 
    FROM (
        SELECT from_id as user_id FROM social_table 
        UNION 
        SELECT to_id as user_id FROM social_table
    )
""")

只需选择

from_id
的所有不同值,然后将它们与
to_id
的所有不同值合并,然后计算此合并集中不同值的数量,这应该会给出两列中唯一用户的总数。


0
投票

您应该从 both

from_id
to_id
列中计算不同的用户。我们可以为此目的使用联合:

SELECT COUNT(DISTINCT id) AS cnt
FROM
(
    SELECT from_id AS id FROM social_table
    UNION ALL
    SELECT to_id FROM social_table
) t;

0
投票

另一个想法是将列连接成一个字符串

from_id || '-' || to_id 

所以你查询将是

curr.execute("Select Count(*) from (Select DISTINCT from_id || '-' || to_id  from social_table)")

0
投票

我猜

from_id
to_id
不应该为空,因此您应该将表定义更正为:

CREATE TABLE social_table (from_id INTEGER NOT NULL, to_id INTEGER NOT NULL);

在这种情况下,您应该使用简单的

COUNT(DISTINCT ...)
,而不是效率较低的
COUNT(*)

sql = """
    SELECT COUNT(*) AS count 
    FROM (
      SELECT from_id FROM social_table 
      UNION 
      SELECT to_id FROM social_table
    )
"""
curr.execute(sql)

因为

UNION
从结果集中删除重复项。

© www.soinside.com 2019 - 2024. All rights reserved.