Mysql - 在子查询

时间:2016-10-22 13:32:36

标签: mysql subquery

我正在尝试获取预定义范围内每天订单的最大和最小结果。

实施例 从1月1日到1月30日,我收到了300份订单。最高销售日的订单数量是多少?什么是最低限度?平均值?

除非我需要这个基于城市的号码,否则这个城市属于另一个查询的结果。

到目前为止我所拥有的:

select count(orderNumber) as total_order_number, 
SUM(cast(REPLACE(total_value, ',', '.') as decimal(8,2))) as total_value, 
avg(cast(REPLACE(total_value, ',', '.') as decimal(8,2))) as average_price,
(count(orderNumber) / 30) as average_order_number,
(select count(*) as total_orders_day from orders where date_created between date('2016-01-01') and date('2016-01-30') group by date(date_created) order by total_orders_day desc limit 1) as max_orders_day,
(select count(*) as total_orders_day from orders where date_created between date('2016-01-01') and date('2016-01-30') group by date(date_created) order by total_orders_day asc limit 1) as min_orders_day,
city
from orders o
where date_created between date('2016-01-01') and date('2016-01-30')
group by o.city
order by total_order_number DESC
limit 7

这给我带来了每个城市的total_order_number,total_value,average_price,average_order_number的结果。但最小值和最大值是相同的,因为我不知道如何按城市分开结果。

任何帮助?

由于

1 个答案:

答案 0 :(得分:0)

对于子查询来说,这似乎是一件简单的事情:

select city, min(numorders), max(numorders), avg(numorders)
from (select city, date(date_created) as dte, count(*) as numorders
      from orders o
      where date_created between date('2016-01-01') and date('2016-01-30')
      group by city, date(date_created)
     ) d
group by city;