问题
先看数据:deliver 表是主表,一个客户会发生多次投递行为:
![](https://img-blog.csdnimg.cn/img_convert/b534d4ba12cfdb7078945455eb337592.png)
deliverItem 表是从表,一个投递行为有多个投递项,delivered 是投递状态(1 表示未完成,2 表示投递完成):
![](https://img-blog.csdnimg.cn/img_convert/5c7f133aca2857caf4cc5efb093ef9e3.png)
需求是统计每个客户下,全部完成的投递行为有几次,未完成(只要存在未完成的投递项,就算作未完成)的投递行为有几次。
解答
自然思路的解题步骤:
1、 在deliverItem表里统计每个投递行为下未完成投递的项目数notDelivered;
2、 上一步结果和deliver表连接在一起,得到新的结果集[customer,notDelivered]
3、 按照customer分组,统计每个customer里notDelivered=0(已完成)个数 / notDelivered>0(未完成)个数
SQL:
select r1.customer,r1.complete,r2.notComplete
from
(select customer, count(*) as complete
from
(select d.customer, d2.notDelivered
from deliver d
left join
(select deliverID,count(*) as notDelivered
from deliverItem