如何解决“您试图执行不包含X作为聚合函数的查询”

时间:2019-05-17 20:51:25

标签: mysql sql

我的数据库中有一个“客户”表,其中包括以下内容:

CustomerID | SupplierID

每个客户都与一个供应商一起插入数据库,这意味着一个特定客户可以被多次列出。

我有一个具有CustomerID = X的特定客户

我正在尝试用SQL编写查询,该查询返回满足以下条件的客户表:用户与X之间的共同供应商数量>客户X的供应商数量的80%。

我成功获取了一个表:

CustomerID1 | CustomerID2 | Num of Mutual Suppliers

其中CustomerID1 = X在所有行中,但我不能包括客户X为了仅选择满足条件的供应商而拥有的供应商的数量。

select user1
     , user2
     , num_in_common
     , COUNT(*)
  from (select f1.CustomerID as user1, f2.CustomerID as user2, count(*) as num_in_common
from Customers f1 inner join
     Customers f2
     on f1.SupplierID = f2.SupplierID
group by f1.CustomerID, f2.CustomerID)
where user1 = X;

我希望收到如下表格:

CustomerID1 | CustomerID2 | Num of Mutual Suppliers | Num of X's Suppliers

但是我收到错误消息“您尝试执行不包含指定表达式'user1'作为聚合函数一部分的查询”。

2 个答案:

答案 0 :(得分:0)

我不认为先前的答案是正确的,所以既然OP澄清了问题,我只是提供了一个更准确的答案。

select x.customerid, c.customerid,
       (count(*) / num_x) as ratio
from customers c cross join
     (select @X as customerid, count(*) as num_x
      from customers c
      where c.customerid = @X
     ) x
where exists (select 1
              from customers cx
              where cx.supplierid = c.supplierid and
                    cx.customerid = @X
             )
group by c.customerid, x.num_x
having count(*) / x.num_x >= 0.8
order by ratio desc;

Here是该代码在语法上正确的证明(无数据)。

Here是一个针对模拟数据的演示。

答案 1 :(得分:0)

通过表的自连接,然后group by进行聚合:

select 
  c.customerid CustomerID1, 
  m.customerid CustomerID2, 
  count(*) num_in_common,
  (select count(*) from customers where customerid = c.customerid) totalofX
from customers c inner join customers m
on m.customerid <> c.customerid and m.supplierid = c.supplierid 
where c.customerid = X 
group by c.customerid, m.customerid
having num_in_common > 0.8 * totalofX

请参见demo