• [1795]. 每个产品在不同商店的价格


    1.题目

    表:Products

    ±------------±--------+
    | Column Name | Type |
    ±------------±--------+
    | product_id | int |
    | store1 | int |
    | store2 | int |
    | store3 | int |
    ±------------±--------+
    这张表的主键是product_id(产品Id)。
    每行存储了这一产品在不同商店store1, store2, store3的价格。
    如果这一产品在商店里没有出售,则值将为null

    请你重构 Products 表,查询每个产品在不同商店的价格,使得输出的格式变为(product_id, store, price) 。如果这一产品在商店里没有出售,则不输出这一行。输出结果表中的 顺序不作要求 。

    2.示例:

    输入:
    Products table:
    +------------+--------+--------+--------+
    | product_id | store1 | store2 | store3 |
    +------------+--------+--------+--------+
    | 0          | 95     | 100    | 105    |
    | 1          | 70     | null   | 80     |
    +------------+--------+--------+--------+
    输出:
    +------------+--------+-------+
    | product_id | store  | price |
    +------------+--------+-------+
    | 0          | store1 | 95    |
    | 0          | store2 | 100   |
    | 0          | store3 | 105   |
    | 1          | store1 | 70    |
    | 1          | store3 | 80    |
    +------------+--------+-------+
    解释:
    产品0在store1,store2,store3的价格分别为95,100,105。
    产品1在store1,store3的价格分别为70,80。在store2无法买到。
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    3.答案

    注意: 价格为null的信息不用输出
    这里只要三个商店,可以查询每个产品每个商店的数据信息拼接起来。

    select product_id,'store1' store,store1 price from products 
    where store1 is not null
    union 
    select product_id,'store2' store,store2 price from products 
    where store2 is not null
    union
    select product_id,'store3' store,store3  price from products 
    where store3 is not null;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    将结果表转为原始表

    注意这里用到了group by分组,select后面只能跟集函数或者分组属性。
    所以 if(store=‘store1’,price,null) store1需要加上集函数,
    sum(if(store=‘store1’,price,null)) store1 或者
    max(if(store=‘store1’,price,null)) store1 或者
    min(if(store=‘store1’,price,null)) store1都可以

    SELECT 
      product_id,
     MAX(IF(store = 'store1', price, NULL)) 'store1',
     SUM(IF(store = 'store2', price, NULL)) 'store2',
     MIN(IF(store = 'store3', price, NULL)) 'store3' 
    FROM
      Products1
    GROUP BY product_id ;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/rearrange-products-table

  • 相关阅读:
    2023NOIP A层联测10 子序列
    Python3 数据结构
    【黄啊码】PHP配合微信小程序实现获取手机号码【直接抄即可】
    用 GPL 开源后想转闭源,法院判决 GPL 协议终身有效;与 Log4j 漏洞斗争是场持久战;Firefox 96 发布 | 开源日报
    MKS PI V1.0使用说明书
    Django model 联合约束和联合索引
    为何红黑树在B/B+树之上仍然占据重要地位?
    优秀的推荐系统架构与应用:从YouTube到Pinterest、Flink和阿里巴巴
    短剧app系统开发(对接广告联盟)源码搭建
    基于 Laravel 封装参数校验
  • 原文地址:https://blog.csdn.net/qq_51758329/article/details/127931142