使用COUNT,GROUP BY,ORDER BY进行SELECT

时间:2012-02-04 09:00:29

标签: mysql

我回来了另一个mysql查询问题。这一次,给定时间范围,我需要选择客户最后一个订单的日期以及客户在该时间范围内的订单总数。

(剥离)查询如下:

SELECT 
   customers_id, 
   customers_name, 
   date_purchased, 
   count(*) as total_order 
FROM orders 
GROUP BY customers_id;

显然,date_purchased返回的时间范围内没有客户的最后订单,但是我不能在分组之前订购,无论如何都要绕过这个?例如,我应该先订购,然后分组(嵌套选择)?

3 个答案:

答案 0 :(得分:3)

select customers_id,
       customers_name,
       MAX(date_purchased) as last_purchase,
       count(*) as total_order
from orders
group by customers_id,customers_name; 

答案 1 :(得分:2)

MAX(date_purchased)如果它是DATE / DATETIME / TIMESTAMP列。如果是字符串,则需要将其转换为MAX(STR_TO_DATE(date_purchased, '%m-%d-%Y'))或任何格式。

关于日期范围...添加WHERE date_purchased BETWEEN '2012-01-01' AND '2012-02-04'或您的范围。如果开始/结束日期不是这种格式,您还需要使用STR_TO_DATE

答案 2 :(得分:0)

select customers_id,
       customers_name,
       MAX(date_purchased) as most_current_purchase_within_range,
       count(*) as total_amount_of_orders
from orders
where (date_purchased between ('2011-01-01') and ('2011-12-31'))
group by customers_id