表: Sales+-------------+-------+| Column Name | Type |+-------------+-------+| sale_id | int || product_id | int || user_id | int || quantity | int |+-------------+-------+sale_id 是该表的主键。product_id 是 product 表的外键。该表的每一行都显示了产品的 ID 和用户购买的数量。表: Product+-------------+------+| Column Name | Type |+-------------+------+| product_id | int || price | int |+-------------+------+product_id 是该表的主键该表的每一行都表示每种产品的价格。编写一个 SQL 查询,为每个用户获取其消费最多的产品 id。如果同一用户在两个或多个产品上花费了最多的钱,请获取所有花费了最多的钱的产品。以 任意顺序 返回结果表。查询结果格式如下所示。示例 1:输入:Sales 表:+---------+------------+---------+----------+| sale_id | product_id | user_id | quantity |+---------+------------+---------+----------+| 1 | 1 | 101 | 10 || 2 | 3 | 101 | 7 || 3 | 1 | 102 | 9 || 4 | 2 | 102 | 6 || 5 | 3 | 102 | 10 || 6 | 1 | 102 | 6 |+---------+------------+---------+----------+Product 表:+------------+-------+| product_id | price |+------------+-------+| 1 | 10 || 2 | 25 || 3 | 15 |+------------+-------+输出:+---------+------------+| user_id | product_id |+---------+------------+| 101 | 3 || 102 | 1 || 102 | 2 || 102 | 3 |+---------+------------+解释:用户 101:- 在产品 1 上花费 10 * 10 = 100。- 在产品 3 上花费 7 * 15 = 105。用户101在产品3上花的钱最多。用户 102:- 在产品 1 上花费 (9 + 7)* 10 = 150- 在产品 2 上花费 6 * 25 = 150- 在产品 3 上花费 10 * 15 = 150。用户 102 在产品 1、2、3 上花的钱最多。来源:力扣(LeetCode)链接:https://leetcode.cn/problems/product-sales-analysis-iv
#测试数据Create table If Not Exists Sales (sale_id int, product_id int, user_id int, quantity int);Create table If Not Exists Product (product_id int, price int);insert into Sales (sale_id, product_id, user_id, quantity) values ('1', '1', '101', '10');insert into Sales (sale_id, product_id, user_id, quantity) values ('2', '3', '101', '7');insert into Sales (sale_id, product_id, user_id, quantity) values ('3', '1', '102', '9');insert into Sales (sale_id, product_id, user_id, quantity) values ('4', '2', '102', '6');insert into Sales (sale_id, product_id, user_id, quantity) values ('5', '3', '102', '10');insert into Sales (sale_id, product_id, user_id, quantity) values ('6', '1', '102', '6');insert into Product (product_id, price) values ('1', '10');insert into Product (product_id, price) values ('2', '25');insert into Product (product_id, price) values ('3', '15');
withtmp as (selecta.user_id,a.product_id,sum(a.quantity*coalesce(b.price,0)) amtfrom Sales aleft join Product bon a.product_id = b.product_idgroup by a.user_id,a.product_id)selectb.user_id,b.product_idfrom (selectuser_id,product_id,rank() over(partition by user_id order by amt desc) rkfrom tmp)bwhere b.rk = 1;


文章转载自跟强哥学SQL,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




