返回介绍

solution / 2300-2399 / 2362.Generate the Invoice / README_EN

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

2362. Generate the Invoice

中文文档

Description

Table: Products

+-------------+------+
| Column Name | Type |
+-------------+------+
| product_id  | int  |
| price     | int  |
+-------------+------+
product_id contains unique values.
Each row in this table shows the ID of a product and the price of one unit.

 

Table: Purchases

+-------------+------+
| Column Name | Type |
+-------------+------+
| invoice_id  | int  |
| product_id  | int  |
| quantity  | int  |
+-------------+------+
(invoice_id, product_id) is the primary key (combination of columns with unique values) for this table.
Each row in this table shows the quantity ordered from one product in an invoice. 

 

Write a solution to show the details of the invoice with the highest price. If two or more invoices have the same price, return the details of the one with the smallest invoice_id.

Return the result table in any order.

The result format is shown in the following example.

 

Example 1:

Input: 
Products table:
+------------+-------+
| product_id | price |
+------------+-------+
| 1      | 100   |
| 2      | 200   |
+------------+-------+
Purchases table:
+------------+------------+----------+
| invoice_id | product_id | quantity |
+------------+------------+----------+
| 1      | 1      | 2    |
| 3      | 2      | 1    |
| 2      | 2      | 3    |
| 2      | 1      | 4    |
| 4      | 1      | 10     |
+------------+------------+----------+
Output: 
+------------+----------+-------+
| product_id | quantity | price |
+------------+----------+-------+
| 2      | 3    | 600   |
| 1      | 4    | 400   |
+------------+----------+-------+
Explanation: 
Invoice 1: price = (2 * 100) = $200
Invoice 2: price = (4 * 100) + (3 * 200) = $1000
Invoice 3: price = (1 * 200) = $200
Invoice 4: price = (10 * 100) = $1000

The highest price is $1000, and the invoices with the highest prices are 2 and 4. We return the details of the one with the smallest ID, which is invoice 2.

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  P AS (
    SELECT *
    FROM
      Purchases
      JOIN Products USING (product_id)
  ),
  T AS (
    SELECT invoice_id, SUM(price * quantity) AS amount
    FROM P
    GROUP BY invoice_id
    ORDER BY 2 DESC, 1
    LIMIT 1
  )
SELECT product_id, quantity, (quantity * price) AS price
FROM
  P
  JOIN T USING (invoice_id);

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

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

发布评论

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