首页 > 解决方案 > 需要准确的输出

问题描述

我是 SQL 新手。我需要知道 SQL 查询才能获得以下场景的输出。

我有一个Campaign有列的表

Customer ID, Campaign Name, Campaign ID, Channel

Channel可以具有以下值之一:

Direct Email, Email, Both

我如何评估为活动联系客户的渠道?例如,有一些客户通过这两个渠道联系过。

如何获得通过这两个渠道联系的客户的数量?请帮我查询。

标签: mysqlsql

解决方案


很简单,我举了个例子。您可以手动检查它。

select count(*) from (select count(*) as b from Campaign group by customer_id) as a where a.b=2;

在这里,首先我们根据我认为不同的 customer_id 对它们进行分组。然后计算已使用两个通道的那些 id。

这是虚拟案例:

+------+------+
| id   | ch   |
+------+------+
|    1 | d    |
|    2 | d    |
|    2 | e    |
|    3 | d    |
|    4 | d    |
|    4 | e    |
|    5 | d    |
|    6 | e    |
+------+------+

inner query: (select count(*) from q group by id);
output: 

       +----------+
        | count(*) |
        +---------+
        |        1 |
        |        2 |
        |        1 |
        |        2 |
        |        1 |
        |        1 |
        +----------+
whole query: mysql> select count(*) 
from (select count(*) as b from q group by id) as a where a.b=2;
        +----------+
        | count(*) |
        +----------+
        |        2 |
        +----------+

一组中的 1 行(0.00 秒)


推荐阅读