Mysql 需要帮助将列按年份和月份分组吗

Mysql 需要帮助将列按年份和月份分组吗,mysql,sql,Mysql,Sql,有人能告诉我为什么在“年度”即第一次查询和“月度”即第二次查询中,总“客户”的总和不同 select year(order_date), year(first_order_date), count(distinct customer_mobile) as 'Customers', count(customer_mobile) as 'Orders', sum(order_amount) from order_table group by year(order_date),year(first_o

有人能告诉我为什么在“年度”即第一次查询和“月度”即第二次查询中,总“客户”的总和不同

select year(order_date), year(first_order_date),
count(distinct customer_mobile) as 'Customers',
count(customer_mobile) as 'Orders',
sum(order_amount)
from order_table
group by year(order_date),year(first_order_date)
vs

谢谢


不同的总和,因为在第一次查询中,您按两年分组

因此,总金额将按年计算

在第二个查询中,您添加了group by month,所有结果都将按月显示,但按年份和按月显示的结果不同

范例

    user1 ---> 40 per year /if you group by year


在第一个查询中,如果客户在一年内有多个订单,则只计算一次。在第二个查询中,客户每年/每月统计一次

您可以在第二个查询中尝试以下操作:

select CONCAT(year(order_date), '-', month(order_date)) as yearmonth,
year(first_order_date),
count(distinct customer_mobile) as 'Customers',
count(customer_mobile) as 'Orders',
sum(order_amount)
from order_table
group by CONCAT(year(order_date), '-', month(order_date)),year(first_order_date)

我现在真的不知道数据是什么样子的,但我猜在第二个查询中,分组“更精细”。也就是说,如果在超过1个月的时间内有订单,它们将在不同的组中,因此您将得到不同的结果。您能帮助我写出正确的查询吗?-谢谢,我什么都不懂。最好给出样品数据和你想要的结果。结果和以前一样…:(
   user1---> 10 january , 10 favruary , 5 mars ,... ///---if you group by month.
select CONCAT(year(order_date), '-', month(order_date)) as yearmonth,
year(first_order_date),
count(distinct customer_mobile) as 'Customers',
count(customer_mobile) as 'Orders',
sum(order_amount)
from order_table
group by CONCAT(year(order_date), '-', month(order_date)),year(first_order_date)