返回介绍

solution / 2300-2399 / 2329.Product Sales Analysis V / README_EN

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

2329. Product Sales Analysis V

中文文档

Description

Table: Sales

+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id   | int   |
| product_id  | int   |
| user_id   | int   |
| quantity  | int   |
+-------------+-------+
sale_id contains unique values.
product_id is a foreign key (column with unique values) to Product table.
Each row of this table shows the ID of the product and the quantity purchased by a user.

 

Table: Product

+-------------+------+
| Column Name | Type |
+-------------+------+
| product_id  | int  |
| price     | int  |
+-------------+------+
product_id contains unique values.
Each row of this table indicates the price of each product.

 

Write a solution to report the spending of each user.

Return the resulting table ordered by spending in descending order. In case of a tie, order them by user_id in ascending order.

The result format is in the following example.

 

Example 1:

Input: 
Sales table:
+---------+------------+---------+----------+
| sale_id | product_id | user_id | quantity |
+---------+------------+---------+----------+
| 1     | 1      | 101   | 10     |
| 2     | 2      | 101   | 1    |
| 3     | 3      | 102   | 3    |
| 4     | 3      | 102   | 2    |
| 5     | 2      | 103   | 3    |
+---------+------------+---------+----------+
Product table:
+------------+-------+
| product_id | price |
+------------+-------+
| 1      | 10  |
| 2      | 25  |
| 3      | 15  |
+------------+-------+
Output: 
+---------+----------+
| user_id | spending |
+---------+----------+
| 101   | 125    |
| 102   | 75     |
| 103   | 75     |
+---------+----------+
Explanation: 
User 101 spent 10 * 10 + 1 * 25 = 125.
User 102 spent 3 * 15 + 2 * 15 = 75.
User 103 spent 3 * 25 = 75.
Users 102 and 103 spent the same amount and we break the tie by their ID while user 101 is on the top.

Solutions

Solution 1

# Write your MySQL query statement below
SELECT user_id, SUM(quantity * price) AS spending
FROM
  Sales
  JOIN Product USING (product_id)
GROUP BY 1
ORDER BY 2 DESC, 1;

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

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

发布评论

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