【发布时间】:2013-12-20 19:03:47
【问题描述】:
这是一段代码,它使用sqlite3 python module 从表history 中获取ID 为itemid 的项目的第N 个百分位数value。
def getNthPercentile(cursor, itemId, N=99.9):
# get 99.9 percentile
# find count of values
cursor.execute("SELECT COUNT(value) FROM history WHERE itemid=?", [itemId])
cnt = int(cursor.fetchone()[0])
# offset gives us teh position of the value in sorted list that represents Nth percentile
offset = int(cnt * (N / 100) - 1)
# sort values
cursor.execute("SELECT value FROM history WHERE itemid = ? ORDER BY value ASC LIMIT 1 OFFSET ?", [itemId, offset])
percentile = float(cursor.fetchone()[0]);
l.debug('itemId=%d, count=%d, offset=%d, %fth percentile=%f' % (itemId, cnt, offset, N, percentile))
# find the (count * pctlVal)th item in sorted values
return percentile
cursor = getDbCursor()
for itemId in listOfItemIds:
print 'Nth percentile for %d is %f' % (itemId, getNthPercentile(cursor, itemId))
问题是:
- 是否可以在单个查询中执行此操作?
- 是否可以在单个查询中为 itemId 列表(而不是一次一个)执行此操作?
【问题讨论】:
标签: python sql sqlite query-optimization