我们有两个表,每个表都有两列。
表1:客户
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
表2:订单
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
我们要计算未下订单的客户的百分比。
显示没有下订单的客户的查询是:
SELECT name AS Customers FROM customers
WHERE id NOT IN (SELECT customerid FROM orders);
这将输出:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
我认为我们可以简单地通过将上面查询的次数除以所有名称的次数来计算百分比,这将给我们50%的答案:
COUNT(SELECT name AS Customers FROM customers
WHERE id NOT IN (SELECT customerid FROM orders)) /
SELECT COUNT(DISTINCT name) FROM customers;
这似乎不起作用。缺少什么?
感谢进阶!
答案 0 :(得分:1)
从订单中获得不同客户ID的数量,然后将其除以客户总数。这将使您下订单的客户比例降低。从1减去该值可得出未下订单的客户比例。乘以100可获得分数的百分比。
SELECT (1
- (SELECT count(DISTINCT customer_id)
FROM orders)
/ count(*))
* 100
FROM customers;