LeetCode # 1070. 产品销售分析 III

1070. 产品销售分析 III

题目

销售表 Sales:

±------------±------+
| Column Name | Type |
±------------±------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
±------------±------+
(sale_id, year) 是这张表的主键(具有唯一值的列的组合)。
product_id 是产品表的外键(reference 列)。
这张表的每一行都表示:编号 product_id 的产品在某一年的销售额。
请注意,价格是按每单位计的。

产品表 Product:

±-------------±--------+
| Column Name | Type |
±-------------±--------+
| product_id | int |
| product_name | varchar |
±-------------±--------+
product_id 是这张表的主键(具有唯一值的列)。
这张表的每一行都标识:每个产品的 id 和 产品名称。

编写解决方案,选出每个售出过的产品 第一年 销售的 产品 id、年份、数量 和 价格。

结果表中的条目可以按 任意顺序 排列。

结果格式如下例所示:

示例 1:

输入:
Sales 表:
±--------±-----------±-----±---------±------+
| sale_id | product_id | year | quantity | price |
±--------±-----------±-----±---------±------+
| 1 | 100 | 2008 | 10 | 5000 |
| 2 | 100 | 2009 | 12 | 5000 |
| 7 | 200 | 2011 | 15 | 9000 |
±--------±-----------±-----±---------±------+
Product 表:
±-----------±-------------+
| product_id | product_name |
±-----------±-------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
±-----------±-------------+
输出:
±-----------±-----------±---------±------+
| product_id | first_year | quantity | price |
±-----------±-----------±---------±------+
| 100 | 2008 | 10 | 5000 |
| 200 | 2011 | 15 | 9000 |
±-----------±-----------±---------±------+

分析

只用一个表就可以,但是不能直接group by分组,分组后只显示一条记录,需要分布查,先找产品id和年份,然后利用id和年份合并查找指定年份的销售记录

题解

# 第一步:先查第一年出售过的产品id
-- select product_id, min(year) from sales group by product_id

# 第二步:计算价格和数量
select product_id, year first_year, quantity, price from sales
where (product_id, year) in (select product_id, min(year) from sales group by product_id)  


相关推荐

  1. LeetCode1070. 产品销售分析 III

    2024-06-06 15:10:02       61 阅读
  2. LeetCode # 1070. 产品销售分析 III

    2024-06-06 15:10:02       31 阅读
  3. 高频SQL 产品销售分析 I

    2024-06-06 15:10:02       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-06 15:10:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-06 15:10:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-06 15:10:02       82 阅读
  4. Python语言-面向对象

    2024-06-06 15:10:02       91 阅读

热门阅读

  1. golang结构与接口方法实现与交互使用示例

    2024-06-06 15:10:02       31 阅读
  2. 设计模式之观察者模式

    2024-06-06 15:10:02       33 阅读
  3. Go语言 一些问题了解

    2024-06-06 15:10:02       31 阅读
  4. BMC压力测试脚本

    2024-06-06 15:10:02       32 阅读
  5. 短剧出海的第一桶金

    2024-06-06 15:10:02       24 阅读
  6. Python怎么睡觉:深入探索Python中的暂停执行机制

    2024-06-06 15:10:02       25 阅读
  7. npm如何发布自己的插件包

    2024-06-06 15:10:02       38 阅读
  8. phpword使用TemplateProcessor对模板进行替换

    2024-06-06 15:10:02       31 阅读
  9. 自动化迁移和更新物体检测XML数据集

    2024-06-06 15:10:02       29 阅读
  10. 03-3.1.2 栈的顺序存储的实现

    2024-06-06 15:10:02       33 阅读
  11. AJAX

    AJAX

    2024-06-06 15:10:02      26 阅读