我有几个重复客户的典型电子商务数据,例如:
customer_id, order_date
1, 2016.05.01
2, 2016.05.02
3, 2016.05.03
1, 2016.05.04
2, 2016.05.05
1, 2016.05.06
我希望输出类似于:
customer_id, 1, 2, 3,
1 2016.05.01 2016.05.04 2016.05.06
1 2016.05.02 2016.05.05
1 2016.05.03
然后我可以轻松地在第一次购买和第二次购买之间获得时间等。如果有一个简单的SQL查询,那么这是在mySQL数据库中
谢谢,Kev
答案 0 :(得分:2)
在MySQL中,最简单的方法可能是使用变量和条件聚合:
select customer_id,
max(case when rn = 1 then order_date end) as order_date_1,
max(case when rn = 2 then order_date end) as order_date_2,
max(case when rn = 3 then order_date end) as order_date_3
from (select t.*,
(@rn := if(@c = customer_id, @rn + 1,
if(@c := customer_id, 1, 1)
)
) as rn
from t cross join
(select @c := -1, @rn := 1) params
order by customer_id, order_date desc
) t
group by customer_id;