首页 > 解决方案 > Python - 从存储在变量中的 SQL 输出中读取特定列

问题描述

我在这里有一个基本问题。我正在提取如下 SQL 输出:

cur = connection.cursor()
cur.execute("""select store_name,count(*) from stores group by store_name""")
data = cur.fetchall() 

上述 SQL 的输出如下:

Store_1,23
Store_2,13
Store_3,43
Store_4,2

我正在尝试读取上述输出中的第 1 列(store_name)。

预期输出:

Store_1
Store_2
Store_3
Store_4

任何人都可以建议我如何做到这一点。谢谢..

标签: pythonsqlpython-3.xamazon-redshift

解决方案


如果我正确理解了你的问题,我想只要纠正你的 SQL 就会给你想要的结果。获取distinctstore_name

select distinct store_name from stores

编辑

回复评论:

尝试以下操作:

from operator import itemgetter
data = cur.fetchall() 
list(map(itemgetter(0), data)) # your answer

推荐阅读