如何将相同的用户ID组合在一起但按时间顺序排列?

时间:2016-04-11 17:40:22

标签: mysql

imei        date
10013700    6:00:00 AM
10015700    6:00:00 AM
10014200    6:00:01 AM
10014500    6:00:04 AM
10016300    6:00:04 AM
16014600    6:00:04 AM
10013700    6:00:05 AM
10015700    6:00:05 AM
10013000    6:00:06 AM
10014700    6:00:06 AM
10016300    6:00:06 AM
10016300    6:00:06 AM

这是由imei和时间组成的表..现在我需要按日期制作表格和imei分组......

imei        date
10013700    6:00:00 AM
10013700    6:00:05 AM
10015700    6:00:00 AM
10015700    6:00:05 AM
10014200    6:00:01 AM
10014500    6:00:04 AM
10016300    6:00:04 AM
10016300    6:00:06 AM
10016300    6:00:07 AM
16014600    6:00:04 AM
10013000    6:00:06 AM
10014700    6:00:06 AM

我已经从最初的时间开始,并且imei与时间一起分组,并在imei的数据集中与其他imei的开始时间旁边的imei号码一起开始,日期还有其他属性..

con = sqlite3.connect("E://code/differenttaxi.sqlite")
df=pd.read_sql_query('SELECT * FROM taxitable WHERE date>="2013-12-16      06:00:00" AND date<"2013-12-17 00:00:00" JOIN (SELECT id,imei, i,lat,lon,speed,direction,error,engine,meter,min(date) first from taxitable group by 10013700)on imei=i ORDER BY first',con)


df.to_csv('E:\\code\\Query_Result.csv',index=False)
con.close()
print("completed!\n")
display(pd.read_csv('E:\\code\\Query_Result.csv'))

生成错误:

  

DatabaseError:sql上的执行失败   “JOIN”附近:语法错误

2 个答案:

答案 0 :(得分:1)

您需要为每个用户找到第一个日期并按顺序排序:

select t.user, t.date
from mytable t
join (select user u, min(date) first from mytable group by 1) x
  on user = u
order by first, user, date

答案 1 :(得分:0)

SELECT tbl.user, tbl.date FROM table_name tbl
LEFT JOIN (
  SELECT user, date FROM table_name GROUP BY user
) ord on tbl.user = ord.user
order by ord.date, tbl.date