Oracle查询购买流行产品的客户

时间:2018-08-11 00:52:49

标签: sql oracle join select subquery

我有三个表:客户,订单和订单项。它们设置如下:

CREATE TABLE cust_account(
cust_id DECIMAL(10) NOT NULL,
first VARCHAR(30),
last VARCHAR(30),
address VARCHAR(50),
PRIMARY KEY (cust_id));

CREATE TABLE orders(
order_num DECIMAL(10) NOT NULL,
cust_id DECIMAL(10) NOT NULL,
order_date DATE,
PRIMARY KEY (order_num));

CREATE TABLE line_it(
order_id DECIMAL(10) NOT NULL,
line_id DECIMAL(10) NOT NULL,
item_num DECIMAL(10) NOT NULL,
PRIMARY KEY (order_id, line_id),
FOREIGN KEY (item_id) REFERENCES products);

我需要编写一个查询,选择要购买3个或更多人购买的商品的客户,他们的姓名和地址。我有以下查询:

SELECT cust_account.cust_id, cust_account.first, cust_account.last, cust_account.address
FROM cust_account
INNER JOIN orders ON cust_account.cust_id = orders.cust_id
INNER JOIN line_it ON orders.order_id = line_it.order_id
GROUP BY cust_account.cust_id, cust_account.last
HAVING COUNT(line_it.item_num) = (
    SELECT COUNT (DISTINCT order_num > 3)
    FROM line_it
    );

我什至需要使其成为子查询吗?我有点迷路。感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

从“三个或更多人购买的物品”开始。您可以通过以下方式获得这些信息:

select li.item_id
from line_item li join
     order_info oi
     on li.order_id = oi.order_id
group by li.item_id
having count(distinct oi.customer_id) >= 3;

现在,您需要该组中的客户。嗯:

select distinct ca.*
from customer_account ca join
     orderinfo oi
     on ca.customer_id = oi.customer_id join
     line_item li
     on li.order_id = oi.order_id
where li.item_id in (select li.item_id
                     from line_item li join
                          order_info oi
                          on li.order_id = oi.order_id
                     group by li.item_id
                     having count(distinct oi.customer_id) >= 3
                    );

您也可以使用窗口功能表达这一点:

select distinct ca.*
from (select ca.*, count(distinct customer_id) over (partition by li.item_id) as num_customers_on_item
      from customer_account ca join
           orderinfo oi
           on ca.customer_id = oi.customer_id join
           line_item li
           on li.order_id = oi.order_id
     ) ca
where num_customers_on_item >= 3;

答案 1 :(得分:0)

您可以使用以下查询

SELECT distinct customer_account.* FROM line_item, order_info ,customer_account  where item_id in (
--Selecting only item purchased 3 or more
SELECT item_id FROM  line_item  group by item_id  having count(1)  >=3
)
and line_item.order_id = order_info.order_id
and customer_account.customer_id = order_info.customer_id
;