[英]group mysql query by field with same value and count
我有一個看起來像這樣的SQL表,但有幾十萬行:
+------+---------------------+-----------+------------+--------------+----------+
| id | timestamp | lat | lon | country_code | city |
+------+---------------------+-----------+------------+--------------+----------+
| 2231 | 2013-09-22 14:58:32 | 28.179199 | 113.113602 | CN | Changsha |
| 2232 | 2013-09-22 14:58:32 | 28.179199 | 113.113602 | CN | Changsha |
| 2233 | 2013-09-22 14:58:32 | 41.792198 | 123.432800 | CN | Shenyang |
| 2234 | 2013-09-22 14:58:32 | 31.045601 | 121.399696 | CN | Shanghai |
| 2235 | 2013-09-22 14:58:32 | 45.750000 | 126.650002 | CN | Harbin |
| 2236 | 2013-09-22 14:58:32 | 39.928902 | 116.388298 | CN | Beijing |
| 2237 | 2013-09-22 14:58:32 | 26.061399 | 119.306099 | CN | Fuzhou |
| 2238 | 2013-09-22 14:58:32 | 26.583300 | 106.716698 | CN | Guiyang |
| 2239 | 2013-09-22 14:58:32 | 39.928902 | 116.388298 | CN | Beijing |
| 2240 | 2013-09-22 14:58:32 | 31.045601 | 121.399696 | CN | Shanghai |
+------+---------------------+-----------+------------+--------------+----------+
我需要根據時間戳(間隔)進行查詢並獲取適合該時間間隔的所有記錄,計算具有相同城市的行(並添加任何項目的緯度/經度,它們對於同一組來說都是相同的)。 目前我的應用程序代碼中只有一個普通的select
和group(如下所示),但這很慢,因為它需要向應用程序發送幾百kb。
(要聚合的python代碼)
sorted_events = sorted(result, key=itemgetter('city'), reverse=False)
for k, g in groupby(sorted_events, key=itemgetter('city')):
group = list(g)
first_item = group[0]
unique_city_item = {
"city" : first_item['city'],
"country_code" : first_item['cc'],
"lon" : first_item['lon'],
"lat" : first_item['lat'],
"number_of_items" : len(group)
}
它按照我想要的方式工作,但速度很慢。 有沒有辦法直接用SQL查詢執行此操作? 我得到以下JSON輸出,我想要類似的東西:
{
{
city: "Baotou",
lon: 109.822197,
country_code: "CN",
lat: 40.652199,
number_of_items: 288
},
{
city: "Beijing,",
lon: 116.388298,
country_code: "CN",
lat: 39.928902,
number_of_items: 47
}
}
這是你想要的?
select city, lon, country_code, lat, count(*) as number_of_items
from table t
where timestamp between STARTTIMESTAMP and ENDTIMESTAMP
group by city, lon, country_code, lat;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.