返回介绍

solution / 1800-1899 / 1867.Orders With Maximum Quantity Above Average / README_EN

发布于 2024-06-17 01:03:13 字数 3483 浏览 0 评论 0 收藏 0

1867. Orders With Maximum Quantity Above Average

中文文档

Description

Table: OrdersDetails

+-------------+------+
| Column Name | Type |
+-------------+------+
| order_id  | int  |
| product_id  | int  |
| quantity  | int  |
+-------------+------+
(order_id, product_id) is the primary key (combination of columns with unique values) for this table.
A single order is represented as multiple rows, one row for each product in the order.
Each row of this table contains the quantity ordered of the product product_id in the order order_id.

 

You are running an e-commerce site that is looking for imbalanced orders. An imbalanced order is one whose maximum quantity is strictly greater than the average quantity of every order (including itself).

The average quantity of an order is calculated as (total quantity of all products in the order) / (number of different products in the order). The maximum quantity of an order is the highest quantity of any single product in the order.

Write a solution to find the order_id of all imbalanced orders.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
OrdersDetails table:
+----------+------------+----------+
| order_id | product_id | quantity |
+----------+------------+----------+
| 1    | 1      | 12     |
| 1    | 2      | 10     |
| 1    | 3      | 15     |
| 2    | 1      | 8    |
| 2    | 4      | 4    |
| 2    | 5      | 6    |
| 3    | 3      | 5    |
| 3    | 4      | 18     |
| 4    | 5      | 2    |
| 4    | 6      | 8    |
| 5    | 7      | 9    |
| 5    | 8      | 9    |
| 3    | 9      | 20     |
| 2    | 9      | 4    |
+----------+------------+----------+
Output: 
+----------+
| order_id |
+----------+
| 1    |
| 3    |
+----------+
Explanation: 
The average quantity of each order is:
- order_id=1: (12+10+15)/3 = 12.3333333
- order_id=2: (8+4+6+4)/4 = 5.5
- order_id=3: (5+18+20)/3 = 14.333333
- order_id=4: (2+8)/2 = 5
- order_id=5: (9+9)/2 = 9

The maximum quantity of each order is:
- order_id=1: max(12, 10, 15) = 15
- order_id=2: max(8, 4, 6, 4) = 8
- order_id=3: max(5, 18, 20) = 20
- order_id=4: max(2, 8) = 8
- order_id=5: max(9, 9) = 9

Orders 1 and 3 are imbalanced because they have a maximum quantity that exceeds the average quantity of every order.

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  t AS (
    SELECT
      order_id,
      MAX(quantity) AS max_quantity,
      SUM(quantity) / COUNT(1) AS avg_quantity
    FROM OrdersDetails
    GROUP BY order_id
  )
SELECT order_id
FROM t
WHERE max_quantity > (SELECT MAX(avg_quantity) FROM t);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文