【发布时间】:2014-02-12 21:34:25
【问题描述】:
我正在处理访问者日志数据,需要按 IP 地址对其进行汇总。数据如下所示:
编号 | ip_address |类型 |留言 | ... ----------+----------------+----------+------------ ----- 1 | 1.2.3.4 |购买 | ... 2 | 1.2.3.4 |访问 | ... 3 | 3.3.3.3 |访问 | ... 4 | 3.3.3.3 |购买 | ... 5 | 4.4.4.4 |访问 | ... 6 | 4.4.4.4 |访问 | ...并且应该总结为:
type="purchase" DESC, type="visit" DESC, id DESC
产量:
选择ID | ip_address |类型 |留言 | ... ----------+----------------+----------+------------ ----- 1 | 1.2.3.4 |购买 | ... 4 | 3.3.3.3 |购买 | ... 6 | 4.4.4.4 |访问 | ...有没有一种优雅的方式来获取这些数据?
一个丑陋的方法如下:
设置@row_num = 0; 如果不存在则创建临时表 tt AS SELECT *,@row_num:=@row_num+1 as row_index FROM log ORDER BY type="purchase" DESC, type="visit" DESC, id DESC 按等级排序;然后得到每个ip_address的最小row_index和id(https://stackoverflow.com/questions/121387/fetch-the-row-which-has-the-max-value-for-a-column)
然后将这些id加入到原来的表中
【问题讨论】:
标签: mysql sql greatest-n-per-group