如果选择“分组依据”,可以在“选择”中使用多个聚合功能吗?

时间:2019-11-17 15:08:25

标签: mysql sql

这是表格:

enter image description here

这是我的查询

import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']

allowed_hosts = [ip, '127.0.0.1']

然后我得到了错误

select sum(if(customer_pref_delivery_date = min(order_date), 1, 0)) immidiate_percentage
from Delivery
group by customer_id;

忽略我要在逻辑上进行的操作,我想知道为什么会收到此错误?当我从Invalid use of group function 中删除sum时,它起作用了,所以我想也许在select中,只能在其中使用一个聚合函数(例如sql)做minselect?是真的吗?

3 个答案:

答案 0 :(得分:1)

您不能将聚合嵌套在选择列表中。
如果要获取与每个客户的订单在同一天需要交付的订单百分比,请执行以下操作:

test[test$id_name %in% keep,]

请参见demo
结果:

select customer_id, 
  100.0 * avg(customer_pref_delivery_date = order_date) immediate_percentage
from Delivery
group by customer_id;

答案 1 :(得分:0)

您不能嵌套聚合功能。这根本没有道理。每个聚合函数每组产生一个值-无法将该值与同一select中组成该组的行进行比较。

我认为您无需再进行任何汇总:

select customer_id, sum( customer_pref_delivery_date = order_date ) as immediate_percentage
from (select d.*,
             min(order_date) over (partition by customer_id) as min_order_date
      from Delivery
     ) d
group by customer_id;

您将总和称为“百分比”似乎很奇怪,但这就是查询中的逻辑。

如果您确实想与每个客户的最短订购日期进行比较,则可以使用窗口功能:

select customer_id, sum( customer_pref_delivery_date = min_order_date ) as immediate_percentage
from (select d.*,
             min(order_date) over (partition by customer_id) as min_order_date
      from Delivery
     ) d
group by customer_id;

答案 2 :(得分:0)

您不能嵌套聚合函数。

一种解决此问题的方法是,在子查询中计算每个客户的最短订购日期,然后将其与原始表联系起来,如下所示:

select 
    d.customer_id
    sum(if(d.customer_pref_delivery_date = dmin.min_order_date), 1, 0)) immidiate_percentage
from 
    delivery d
    inner join (
        select customer_id, min(order_date) min_order_date
        from delivery
        group by customer_id
    ) dmin on dmin.customer_id = d.customer_id
group by d.customer_id;

在MySQL 8.0中,您可以使用窗口函数:

select
    d.customer_id,
    sum(if(customer_pref_delivery_date = min_order_date), 1, 0)) immidiate_percentage   
from (
    select 
        customer_id, 
        customer_pref_delivery_date,
        min(order_date) over(partition by customer_id) min_order_date
    from delivery
) t
group by customer_id