我有一个列出order_id,order_date和user_id的表。
我没有问题检索每个客户订单的数量,并在order_id旁边显示。但是,我一直尝试失败的是在每个order_id旁边显示每个客户的第n个订单值。
SELECT order.id,
order.user_id,
date(from_unixtime(order.created_date))
COUNT(order2.id)
FROM order order
JOIN order order2
ON order2.user_id = order.user_id
AND order2.created_date <= order.created_date
GROUP
BY order.user_id,
date(from_unixtime(order.created_date)),
order.id
ORDER
BY order.user_id,
date(from_unixtime(order.created_date)),
order.id;
这只给出了每个订单的每个订单的订单总数,而不是第n个值。
结果应该是这样的:
created_date order_id user_id order_number
2016-11-21 234 12 2
2016-10-15 123 16 1
2016-10-03 234 12 1
提前多多感谢!
答案 0 :(得分:0)
好吧,你可以添加另一个连接并稍后更改第一个:
SELECT order.id,
order.user_id,
date(from_unixtime(order.created_date))
COUNT(distinct order3.id) - COUNT(distinct order2.id)
FROM order order
JOIN order order2
ON order2.user_id = order.user_id
AND order2.created_date > order.created_date
JOIN order order3
ON order2.user_id = order.user_id
GROUP
BY order.user_id,
date(from_unixtime(order.created_date)),
order.id
ORDER
BY order.user_id,
date(from_unixtime(order.created_date)),
order.id;