sql - 获得从特定客户群购买的产品的百分比
问题描述
问题很简单,假设我们有一张包含客户、购买和产品的表格。客户(cust_id,名称,状态)包含所有用户数据,购买包含购买数据(数量,价格,prod_id,cust_id),产品包含产品信息(prod_id,描述)。
假设我有 10 个客户,其中 10 个客户中有 6 个买了鞋子,6 个中有 2 个买了鞋带。
我的目标是让那 6 名购买鞋子的顾客获得购买鞋带的那 6 名顾客的百分比。所以我的百分比应该在 33.33% 左右。
我多次尝试这样做,INNER JOINS
但似乎我做得不对。我对这个简单问题的查询非常混乱,过去几天我一直在尝试解决这个问题。PS 我是 SQL 查询的新手。我从来没有做过这些复杂的查询。
WITH state_product(customers_id, products_id) AS (
SELECT DISTINCT customers.id, products.id
FROM customers
INNER JOIN purchases ON purchases.customer_id = customers.id
INNER JOIN products ON purchases.product_id = products.id
WHERE products.id = 7
), WITH specific_product(customers_id, products_id) AS (
SELECT DISTINCT customers.id, products.id from customers
INNER JOIN purchases ON purchases.customer_id = customers.id
INNER JOIN products ON purchases.product_id = products.id
INNER JOIN state_product ON customers.id =
state_product.customers_id WHERE products.id = 8),
SELECT SUM(*)/COUNT(state_product.customer_id)*100
AS Percentage
FROM specific_product;
当我编写此代码时,我的逻辑是让所有customers.id
购买鞋子的人都在一张桌子上用他们的products.id
PK 购买鞋子,7
然后调用那张桌子state_product
。
然后从里面找另一张桌子和state_product
顾客一起,把买鞋带的顾客products.id = 8
拿来specific_product
。哪个应该给我两个customers.id
。
现在得到百分比,我只是得到specific_product
记录的总和,即 2,然后将其除以总和,state_product
然后乘以 100,然后将其放入名为 的表中percentage
。这将是 (2/6)*100 = 33.33%
我愿意用一种更简单的方法来解决这个问题JS 来解决这个问题。鼓励建设性的批评。
解决方案
问题
假设我有 10 个客户,其中 10 个客户中有 6 个买了鞋子,6 个中有 2 个买了鞋带。
我的目标是让那 6 名购买鞋子的顾客获得购买鞋带的那 6 名顾客的百分比。所以我的百分比应该在 33.33% 左右。
用户输入
-- 3张桌子
--客户(cust_id,名称,状态)
- -- 采购(数量、价格、prod_id、cust_id)
- --产品信息(prod_id,描述)
他们买的东西的清单。
select
b.cust_id,c.description as product
into #temp
from purchase a join customers b on a.cust_id = b.cust_id
join product_info c on a.prod_id = c.prod_id
where c.description in ('shoes','laces')
现在查询逻辑
select
t1.cust_id,
sum(case
when t2.cust_id is null then 0
else 1
end) totalCustomersWithLaces
into #t2
from
(
--List of customers who bought shoes
select distinct cust_id from #temp
where product = "shoes"
)t1 left join
(
--List of customers who bought laces
select distinct cust_id from #temp
where product = "laces"
)t2 on t1.cust_id = t2.cust_id
最后得到你的结果
select sum(totalCustomersWithLaces)/cast(count(1) as float) from #t2
推荐阅读
- macos - 无法使用 [command] --help 或 -h 获取有关 Mac OS 终端中命令的帮助
- powershell - Windows 终端不使用 dir 命令打印文件
- javascript - 如何在 Blogger 中创建多语言博客?
- c# - 如何从主窗体控制或停止动态用户控件的绘制事件?
- ssl - RabbitMQ 集群算子 - 启用 MQTT 插件
- flutter - Flutter:在“...List”中使用的函数列表导致“避免使用不必要的语句”并且不起作用
- excel - 不同计算机上图形的大小和位置 VBA EXCEL
- javascript - Vue 异步组件不适用于 Webpack 热模块替换
- django - 如何以 DRY 方式创建带有嵌套 url 的 rest api?
- python - 我正在使用简单的神经网络来解决 IRIS 数据集问题。NN 的输出是多标签多类而不是单标签