首页 > 解决方案 > 获得从特定客户群购买的产品的百分比

问题描述

问题很简单,假设我们有一张包含客户、购买和产品的表格。客户(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.idPK 购买鞋子,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 来解决这个问题。鼓励建设性的批评。

标签: sqlpostgresql

解决方案


问题

  • 假设我有 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

推荐阅读