SELECT GROUP BY一个标准,COUNT个另一个标准

时间:2018-04-09 17:58:18

标签: sql sql-server select

我做了一个营销活动,我的一些客户收到了两种类型的通讯(A和B),这些类型分为3类。

我在SQL Server 2012数据库中有2个表:<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <body> <div class="container"> <p id="paragraph">word is sold</p> </div> </body>payment

最终我需要的是SEGMENT的付款率(世界卫生组织支付/世界卫生组织联系) 我这样做没有问题,但现在营销团队以不同的方式对费率组进行了分析:

按部门划分A,收到多少部分B以及如何支付B部分

就像那样:

contacts

表的内容是:

联系

+---------+----------+------+
| SEGMENT | RECEIVED | PAID |
+---------+----------+------+
| A1      | 2        | 1    | 
| A2      | 1        | 1    |
+---------+----------+------+

PAYMENTS

+----+---------+------------+
| ID | SEGMENT | DATE       |
+----+---------+------------+
| 1  | A1      | 2018-03-01 |
| 1  | B7      | 2018-03-10 |
| 2  | A2      | 2018-03-01 |
| 2  | B5      | 2018-03-10 |
| 3  | A1      | 2018-03-01 |
| 3  | B7      | 2018-03-10 |
| 4  | A3      | 2018-03-01 |
| 5  | A1      | 2018-03-01 |
+----+---------+------------+

我很难做到这一点。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

您的数据结构和问题有点难以理解。但我想我明白了。您希望在两个细分中联系客户,然后了解“a”细分受支付的数量。

如果我假设联系人只是一个段,那么我可以这样做:

select c.a_segment, count(*) as num_received, count(p.id) as num_paid
from (select id, sum(case when segment like 'A%' then 1 else 0 end) as in_a,
             sum(case when segment like 'B%' then 1 else 0 end) as in_b,
             max(case when segment like 'A%' then segment end) as a_segment
      from contacts
      group by id
     ) c left join
    payments p
    on c.id = p.id
where c.in_b = 1 and c.in_a = 1
group by c.a_segment;