Вот кусок кода, который использует sqlite3
python module для извлечения Nth процентиля value
для элемента с идентификатором itemid
из таблицы history
.SQLite, как оптимизировать запрос для N-го процентиля
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))
Вопросов:
- Можно ли сделать это в одном запросе?
- Возможно ли это сделать для списка itemIds (вместо одного за раз) в одном запросе?
Спасибо за внимание. Это, в некотором роде, отвечает на мой вопрос. Не то, на что я надеялся, но ... – Kashyap