我正在编写查询以获取所有客户信息并显示他们上次订购的时间。我目前的疑问是:
SELECT
`user`.fname,
`user`.lname,
`user`.email,
`order`.orderplaced_ts,
COUNT(*) AS Total
FROM `order`
INNER JOIN `user` ON `order`.user_id = `user`.id
WHERE `order`.store_id = 10
AND `order`.orderplaced_ts > "2015-01-01 00:00:00"
AND `order`.order_status != "Cancelled"
GROUP BY `order`.user_id
ORDER BY `order`.orderplaced_ts
我在ORDER BY order.orderplaced_ts
之后尝试了ASC和DESC,但仍然没有返回我想要的内容。
编辑:当前结果
First Last Email Date Count
Lisa Day email@something.com 2015-01-08 13:16:31 105
Alex Sullivan email@something.com 2015-01-05 11:48:33 90
Jill GORDON email@something.com 2015-01-02 12:52:57 68
Bob Jain email@something.com 2015-03-23 12:39:24 62
Jack Merkher email@something.com 2015-01-05 11:19:31 56
日期字段显示他们第一次订购,而我想要的是他们最后一次订购。
期望的结果将是:
First Last Email Date Count
Lisa Day email@something.com 2015-07-08 13:16:31 105
Alex Sullivan email@something.com 2015-07-05 11:48:33 90
Jill GORDON email@something.com 2015-07-02 12:52:57 68
Bob Jain email@something.com 2015-07-23 12:39:24 62
Jack Merkher email@something.com 2015-07-05 11:19:31 56
SELECT *的样本数据:
ID User_ID Store_ID orderplaced_ts
1104121 214831 10 2015-01-02 11:04:49
1104261 559281 10 2015-01-02 11:21:34
1104791 420461 10 2015-01-02 12:10:34
1105041 801481 10 2015-01-02 12:33:58
1105051 216501 10 2015-01-02 12:35:28
1105191 814661 10 2015-01-02 12:42:26
1105241 304571 10 2015-01-02 12:44:31
1105321 781611 10 2015-01-02 12:52:41
1105331 528411 10 2015-01-02 12:52:57
1105641 752171 10 2015-01-02 13:36:10
1106061 458791 10 2015-01-02 15:46:24
所以我要做的就是让所有用户,他们订购了多少次以及他们最近的订单是什么。
内部联接只是检索用户电子邮件,名字和姓氏。
解决问题的我的最终查询如下所示:
SELECT
`user`.fname,
`user`.lname,
`user`.email,
COUNT(*) AS Total_Orders,
`order`.orderplaced_ts AS First_Order,
MAX(order.orderplaced_ts) AS Last_Order
FROM `order`
INNER JOIN `user` ON `order`.user_id = `user`.id
WHERE `order`.store_id = 10
AND `order`.orderplaced_ts > "2015-01-01 00:00:00"
AND `order`.order_status != "Cancelled"
GROUP BY `order`.user_id ASC
ORDER BY `order`.orderplaced_ts
答案 0 :(得分:3)
Group By
子句中不包含的所有选定值必须具有sum
或max
等聚合函数。
否则,分组选择将无法知道要显示的值。
我建议您按user.fname
,user.lname
和user.email
而非order.user_id
根据@Uueerdo的评论:按MAX(order.orderplaced_ts)
排序可以解决问题