在sqlite3中使用group by函数或在python中使用itertools.groupby,对字符串中间值进行排序和分组
我有一个连接到SQLite数据库的代码,它能返回“phone1”这一列的数据。我想跳过区号部分,按照“phone1”列中间的交换码部分进行排序。如果我测试一个已知的交换码,使用通配符似乎是有效的,但我想要的是按照以5个字符开头的内容进行分组或排序。
first_name, last_name, company, address, city, county, state, zip, phone1, phone2, email, web
(0, ('201-238-5688',))
(1, ('201-431-2989',))
(2, ('201-474-4924',))
(3, ('201-588-7810',))
(4, ('201-672-1553',))
.....
(495, ('973-943-3423',))
(496, ('978-626-2978',))
(497, ('978-697-6263',))
(498, ('979-718-8968',))
(499, ('985-890-7262',))
import os, csv, json, re
import sqlite3
conn = sqlite3.connect('US_500.sqlite')
conn.text_factory = str
cursor = conn.cursor()
reader = cursor.execute ("SELECT phone1 FROM SampleData ORDER BY substr(phone1, 5) BETWEEN 200 AND 300")
tabledata = cursor.fetchall()
for row in enumerate(tabledata):
print str(row)
conn.close()
1 个回答
1
我觉得你不需要分组,排序就足够了。
在SQL查询中,你可以使用substr()
这个函数来选择字段的一部分,然后根据这个部分进行排序。你的查询可以是:
SELECT phone1 FROM SampleData order by substr(phone1, 5, 3)
这个函数会从第5个位置开始提取3个字符(也就是第5、6和7个字符),并用这些字符来进行排序。
同样的,你也可以在Python中做到这一点,通过对查询结果调用sorted()
,并传入一个选择字符范围的函数来进行排序:
tabledata = cursor.fetchall()
for row in enumerate(sorted(tabledata, key=lambda x: x[4:7])):
print str(row)