计算客户购买商品的平均价格

时间:2018-08-11 20:43:36

标签: sql oracle join subquery where

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

JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content)

使用Oracle,我需要编写一个查询,该查询显示购买次数超过5次或以上的那些客户的平均商品价格。这就是我一直在努力的事情:

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 lines(
order_num DECIMAL(10) NOT NULL,
line_id DECIMAL(10) NOT NULL,
item_num DECIMAL(10) NOT NULL,
price DECIMAL(10),
PRIMARY KEY (order_id, line_id),
FOREIGN KEY (item_id) REFERENCES products);

2 个答案:

答案 0 :(得分:2)

  1. ... INNER JOIN一起摆在您的所有桌子上
  2. ... GROUP BY个客户并计算每个客户行的平均价格
  3. ...使用HAVING子句将结果限制为购买5次或以上的组

由于这闻起来像作业,所以我会在长时间的停顿后发布完整答案...

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.


SELECT   ca.first, ca.last, avg(l.price) avg_price
FROM     cust_account ca
INNER JOIN orders o ON o.cust_id = ca.cust_id
INNER JOIN lines l ON l.order_num = o.order_number
GROUP BY ca.first, ca.last
HAVING COUNT(distinct l.line_id) >=5
-- OR, maybe your requirement is ...
-- HAVING COUNT(distinct o.order_num) >= 5
-- ... the question was a bit unclear on this point

答案 1 :(得分:1)

我认为就是这样。我认为它不会立即起作用(我对oracle一无所知),但我认为您会明白的:

SELECT orders.cust_id,
       AVG(lines.price) AS average_price
FROM lines
JOIN orders ON orders.order_num = orders.order_num
WHERE orders.cust_id IN (SELECT orders.cust_id
                         FROM orders
                         GROUP BY orders.cust_id
                         HAVING COUNT(*) >= 5)
GROUP BY orders.cust_id;

子查询选择具有5个以上订单的客户。 而主查询只是从该客户的所有订单中获取所有行。

我想您可以使用HAVING DISTINCT ...消除子查询。无论如何,带有子查询的代码应该可以正常工作。

UPD。

类似的东西

SELECT orders.cust_id,
       AVG(lines.price) AS average_price
JOIN orders ON orders.order_num = orders.order_num
GROUP BY orders.cust_id
HAVING COUNT(DISTINCT orders.id) >= 5;