基于跨产品使用的 SQL 计数

问题描述 投票:0回答:1

我有以下数据,我正在尝试弄清楚如何构建 SQL 查询来计算使用 Bathroom 产品并且也在使用 Kitchen 产品的客户。

示例 1:吉姆使用厨房产品 b 并且正在使用我们的 浴室 产品,因此我想显示产品 b 的计数为 1。

示例 2: Pete 同时使用厨房产品 ac 并且正在使用我们的 Bathroom 产品,因此我想显示 ac 的计数均为 1。

示例 3: Abby 不使用任何厨房产品,所以我不在乎她目前使用我们的浴室产品。我不需要为她计数。

所需输出:

厨房产品 使用卫浴产品的顾客数量
a 2
b 3
c 2

表格数据:

客户 产品_lvl_1 产品_lvl_2
艾比 浴室 浴室
厨房 a
吉姆 浴室 浴室
吉姆 厨房 b
浴室 浴室
厨房 b
皮特 浴室 浴室
皮特 厨房 c
皮特 厨房 a
罗宾 浴室 浴室
罗宾 厨房 a
莎莉 厨房 b
汤姆 浴室 浴室
汤姆 厨房 b
汤姆 厨房 c

数据如下:

create table customer_prods
(
    customer varchar(30),
    product_lvl_1 varchar(30),
    product_lvl_2 varchar(30),
    revenue number
)

INSERT INTO customer_prods
    (customer,product_lvl_1,product_lvl_2,revenue)
VALUES
    ('Abby','Bathroom','Bathroom',1),
    ('Jean','Kitchen','a',6),
    ('Jim','Bathroom','Bathroom',6),
    ('Jim','Kitchen','b',8),
    ('Joe','Bathroom','Bathroom',7),
    ('Joe','Kitchen','b',6),
    ('Pete','Bathroom','Bathroom',9),
    ('Pete','Kitchen','c',2),
    ('Pete','Kitchen','a',8),
    ('Robin','Bathroom','Bathroom',7),
    ('Robin','Kitchen','a',9),
    ('Sally','Kitchen','b',6),
    ('Tom','Bathroom','Bathroom',8),
    ('Tom','Kitchen','b',7),
    ('Tom','Kitchen','c',8);
sql oracle
1个回答
0
投票

这将获得厨房产品列表以及购买该产品的客户数量,以及任何浴室产品:

Select  kp.Product_Lvl_2 Kitchen_Product, Count(c.Customer) Customer_Count
From    Customer_Prods kp,
        Customer_Prods c
Where   kp.Product_Lvl_1 = 'Kitchen'
And     kp.Product_Lvl_2 = c.Product_Lvl_2
And     kp.Customer = c.Customer
And     kp.Customer In (
    Select  bp.Customer
    From    Customer_Prods bp
    Where   bp.Product_Lvl_1 = 'Bathroom'
)
Group By kp.Product_Lvl_2
Order By Kitchen_Product;
© www.soinside.com 2019 - 2024. All rights reserved.