Count未返回正确的值

时间:2016-06-19 15:25:33

标签: mysql sql

我有2张桌子。

table_orders - order_id, order_datetime
table_order_details - order_id, product_sell_price, quantity

我希望按月份的订单数量获得总销售额。这是我的疑问。

select SUM(OD.product_sell_price * OD.quantity) Total,
    count(O.order_id) Count, MONTH(order_datetime) Month,
    MONTHNAME(order_datetime) MonthName, YEAR(order_datetime) YEAR 
from 
table_orders O 
INNER JOIN 
table_order_details OD
    ON O.order_id = OD.order_id 
group by MONTH(order_datetime), YEAR(order_datetime)
order by order_datetime;

除了该月的订单数量外,所有值都是正确的。我认为它在两个表的INNER JOIN之后给出了order_id的计数。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:3)

只需使用COUNT (DISTINCT column)即可确保您只计算唯一订单ID

select SUM(OD.product_sell_price * OD.quantity) Total,
       count(DISTINCT O.order_id) Count,
       MONTH(order_datetime) Month,
       MONTHNAME(order_datetime) MonthName,
       YEAR(order_datetime) YEAR
from table_orders O
INNER JOIN table_order_details OD 
 ON O.order_id = OD.order_id
group by MONTH(order_datetime), YEAR(order_datetime)
order by order_datetime;