You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL查询结果按产品分组,合并投票字段为列表

解决方案

方法一:Python端分组处理

用字典按(product, model, creator)作为唯一键分组,收集对应vote值:

# 执行查询
cursor_test.execute("SELECT product, model, creator, vote FROM sales")

# 初始化分组字典
result_dict = {}
for product, model, creator, vote in cursor_test.fetchall():
    key = (product, model, creator)
    if key not in result_dict:
        result_dict[key] = []
    result_dict[key].append(vote)

# 转换为目标格式输出
for key, votes in result_dict.items():
    print( (key[0], key[1], key[2], votes) )

运行后输出:

('iMac 24', '24', 'Apple', [8, 9, 10])
('HP 24', '24-Cb1033nl', 'HP', [7, 6, 7])

方法二:SQL端直接聚合

根据你使用的数据库类型,用对应聚合函数在查询阶段完成合并:

MySQL/MariaDB

使用GROUP_CONCAT拼接vote值,再在Python中转成列表:

SELECT product, model, creator, GROUP_CONCAT(vote SEPARATOR ',') AS votes
FROM sales
GROUP BY product, model, creator

Python处理代码:

cursor_test.execute("""
    SELECT product, model, creator, GROUP_CONCAT(vote SEPARATOR ',') AS votes
    FROM sales
    GROUP BY product, model, creator
""")
for row in cursor_test.fetchall():
    product, model, creator, votes_str = row
    votes = list(map(int, votes_str.split(',')))
    print( (product, model, creator, votes) )

PostgreSQL

使用array_agg直接返回数组,Python中可直接转为列表:

SELECT product, model, creator, array_agg(vote) AS votes
FROM sales
GROUP BY product, model, creator

Python处理代码:

cursor_test.execute("""
    SELECT product, model, creator, array_agg(vote) AS votes
    FROM sales
    GROUP BY product, model, creator
""")
for row in cursor_test.fetchall():
    print(row)

SQLite

同样用GROUP_CONCAT,处理逻辑和MySQL一致:

SELECT product, model, creator, GROUP_CONCAT(vote) AS votes
FROM sales
GROUP BY product, model, creator

内容的提问来源于stack exchange,提问作者user20801151

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:55:16