繁体   English   中英

如何从另一个表加入计数(*)

[英]How to join the count(*) from another table

我在这里有一个问题,如何将 count(*) 从另一个表连接到基础表。

问题如下:

表:客户

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| customer_id | int     |
| product_key | int     |
+-------------+---------+

product_key 是 Product 表的外键。

表:产品

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_key | int     |
+-------------+---------+

product_key 是该表的主键列。

为报告编写 SQL 查询,该报告提供客户表中购买了 Product 表中所有产品的客户 ID。

例如:

客户表:

+-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1           | 5           |
| 2           | 6           |
| 3           | 5           |
| 3           | 6           |
| 1           | 6           |
+-------------+-------------+

产品表:

+-------------+
| product_key |
+-------------+
| 5           |
| 6           |
+-------------+

结果表:

+-------------+
| customer_id |
+-------------+
| 1           |
| 3           |
+-------------+

购买了所有产品(5 和 6)的客户是 id 为 1 和 3 的客户。

我的方法是:

select distinct 
c.customer_id 
from customer as c join (
    select 
    count(distinct product_key) as total 
    from product 
) as t 
group by c.customer_id 
having count(distinct c.product_key) = t.total

但我会遇到错误消息:

Unknown column 't.total' in 'having clause'

你介意弄清楚我哪里做错了吗? 感谢您在高级方面的帮助。

您不需要HAVING子句。 您正在尝试在 SQL 中加入笛卡尔连接。 我怀疑聚合适用于笛卡尔积。

下面 SQL 将返回拥有所有产品的客户列表 -

select customer_id from (select customer_id, count(distinct p.product_key) product_count
from customer c 
join product p on c.product_key = p.product_key
group by c.customer_id) t
where t.product_count = (select count(distinct product_key) from product);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM