单挑力扣(LeetCode)SQL题:1549. 每件商品的最新订单(难度:中等)

相信很多学习SQL的小伙伴都面临这样的困境,学习完书本上的SQL基础知识后,一方面想测试下自己的水平;另一方面想进一步提升,却不知道方法。

其实,对于技能型知识,我的观点一贯都是:多练习、多实践。正所谓实践出真知,学完书本的知识,很多时候也只能做到知道,距离熟练的应用还差的很远。

在咱们程序员圈子里,力扣(LeetCode)和牛客(nowcoder.com)是两个公认比较好的实践平台。题库比较多,还有不少大厂的笔试真题,特别适合找工作时撸一撸。当然,作为平时个人技术提升的练习题,也是非常不错的。

最近一段时间,我会先从力扣(LeetCode)的SQL题刷起。当然,顺序可能是随机的,欢迎小伙伴们点题。

题目:1549. 每件商品的最新订单

(通过次数5,893 | 提交次数8,629,通过率68.29%)

表: Customers
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| name          | varchar |
+---------------+---------+
customer_id 是该表主键.
该表包含消费者的信息.表: Orders
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| customer_id   | int     |
| product_id    | int     |
+---------------+---------+
order_id 是该表主键.
该表包含消费者customer_id产生的订单.
不会有商品被相同的用户在一天内下单超过一次.表: Products
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
| price         | int     |
+---------------+---------+
product_id 是该表主键.
该表包含所有商品的信息.写一个SQL 语句, 找到每件商品的最新订单(可能有多个).
返回的结果以 product_name 升序排列, 如果有排序相同, 再以 product_id 升序排列. 如果还有排序相同, 再以 order_id 升序排列.
查询结果格式如下例所示。示例 1:输入:
Customers表:
+-------------+-----------+
| customer_id | name      |
+-------------+-----------+
| 1           | Winston   |
| 2           | Jonathan  |
| 3           | Annabelle |
| 4           | Marwan    |
| 5           | Khaled    |
+-------------+-----------+
Orders表:
+----------+------------+-------------+------------+
| order_id | order_date | customer_id | product_id |
+----------+------------+-------------+------------+
| 1        | 2020-07-31 | 1           | 1          |
| 2        | 2020-07-30 | 2           | 2          |
| 3        | 2020-08-29 | 3           | 3          |
| 4        | 2020-07-29 | 4           | 1          |
| 5        | 2020-06-10 | 1           | 2          |
| 6        | 2020-08-01 | 2           | 1          |
| 7        | 2020-08-01 | 3           | 1          |
| 8        | 2020-08-03 | 1           | 2          |
| 9        | 2020-08-07 | 2           | 3          |
| 10       | 2020-07-15 | 1           | 2          |
+----------+------------+-------------+------------+
Products表:
+------------+--------------+-------+
| product_id | product_name | price |
+------------+--------------+-------+
| 1          | keyboard     | 120   |
| 2          | mouse        | 80    |
| 3          | screen       | 600   |
| 4          | hard disk    | 450   |
+------------+--------------+-------+
输出:
+--------------+------------+----------+------------+
| product_name | product_id | order_id | order_date |
+--------------+------------+----------+------------+
| keyboard     | 1          | 6        | 2020-08-01 |
| keyboard     | 1          | 7        | 2020-08-01 |
| mouse        | 2          | 8        | 2020-08-03 |
| screen       | 3          | 3        | 2020-08-29 |
+--------------+------------+----------+------------+
解释:
keyboard 的最新订单在2020-08-01, 在这天有两次下单.
mouse 的最新订单在2020-08-03, 在这天只有一次下单.
screen 的最新订单在2020-08-29, 在这天只有一次下单.
hard disk 没有被下单, 我们不把它包含在结果表中.来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/the-most-recent-orders-for-each-product

#测试数据
Create table If Not Exists Customers (customer_id int, name varchar(10));
Create table If Not Exists Orders (order_id int, order_date date, customer_id int, product_id int);
Create table If Not Exists Products (product_id int, product_name varchar(20), price int);insert into Customers (customer_id, name) values ('1', 'Winston');
insert into Customers (customer_id, name) values ('2', 'Jonathan');
insert into Customers (customer_id, name) values ('3', 'Annabelle');
insert into Customers (customer_id, name) values ('4', 'Marwan');
insert into Customers (customer_id, name) values ('5', 'Khaled');insert into Orders (order_id, order_date, customer_id, product_id) values ('1', '2020-07-31', '1', '1');
insert into Orders (order_id, order_date, customer_id, product_id) values ('2', '2020-7-30', '2', '2');
insert into Orders (order_id, order_date, customer_id, product_id) values ('3', '2020-08-29', '3', '3');
insert into Orders (order_id, order_date, customer_id, product_id) values ('4', '2020-07-29', '4', '1');
insert into Orders (order_id, order_date, customer_id, product_id) values ('5', '2020-06-10', '1', '2');
insert into Orders (order_id, order_date, customer_id, product_id) values ('6', '2020-08-01', '2', '1');
insert into Orders (order_id, order_date, customer_id, product_id) values ('7', '2020-08-01', '3', '1');
insert into Orders (order_id, order_date, customer_id, product_id) values ('8', '2020-08-03', '1', '2');
insert into Orders (order_id, order_date, customer_id, product_id) values ('9', '2020-08-07', '2', '3');
insert into Orders (order_id, order_date, customer_id, product_id) values ('10', '2020-07-15', '1', '2');insert into Products (product_id, product_name, price) values ('1', 'keyboard', '120');
insert into Products (product_id, product_name, price) values ('2', 'mouse', '80');
insert into Products (product_id, product_name, price) values ('3', 'screen', '600');
insert into Products (product_id, product_name, price) values ('4', 'hard disk', '450');

解题思路:

跟8月23日的推文《1077. 项目员工 III》一样,这道题考查的也是分组内排名,然后返回前N名的写法。

但是也有2点特殊要求:

第一,如果最新的一天有多条记录,那么都需要返回;

第二,对于返回的结果,需要按要求排序:返回的结果以 product_name 升序排列, 如果有排序相同, 再以 product_id 升序排列. 如果还有排序相同, 再以 order_id 升序排列

那么,在实现上,也主要是分为以下3个步骤:

第一步,先计算出每个产品每个订单日期的排名(倒序),如果最新的日期内有多笔订单,则需要全部返回。

针对这类分组内排序后取前N名的需求,有三个分析函数可以使用,分别是:row_number、rank、dense_rank。

根据需求,这里比较适合使用的是rank和dense_rank,然后限定排序序号为1即可。

第二步,关联出返回结果中需要的product_name。可以使用product_id与Products关联,获取product_name的值。

第三步,使用order by子句,对返回的结果集进行排序。

参考SQL:


selectc.product_name,b.product_id,b.order_id,b.order_date
from (selecta.product_id,a.order_id,a.order_date,rank() over(partition by a.product_id order by order_date desc) rkfrom Orders a
)b
left join Products c
on b.product_id = c.product_id
where b.rk = 1
order by c.product_name,b.product_id,b.order_id;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/380700.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php常量变量连接,PHP常量及变量区别原理详解

常量:用于储存一个不会变化也不希望变化的数据的标示符(命名规则与变量相同)定义形式:使用 define() 函数定义使用形式:define(“常量名” ,常量值)使用 counst 语法定义使用形式:counst 常量名 常量值使用常量&#…

js生成随机数

Math.round(Math.random() * 10000) 父窗口弹出子窗口,子窗口选择值后,赋值到父窗口的某个控件上 父窗口代码: function fn_GetMarksClassModel() { var url "SelectMarksClassModel.aspx?temp" Math.round(Math.random(…

字符串最长回文子串_最长回文子串

字符串最长回文子串Problem statement: 问题陈述&#xff1a; Given a string str, find the longest palindromic substring. A substring need to be consecutive such that for any xixj i<j must be valid in the parent string too. Like "incl" is a subst…

一个人在办公室的日子

同我一起工作的那个大学同学兼同事ALICE因为个人原因,最近请假了一个星期.剩下了孤单的我在公司应付日常英文翻译书写工作。的确有点闷&#xff0c;的确有些不习惯&#xff0c;点讲&#xff0c;习惯了两个人一起吃饭聊天&#xff0c;一起拼命赶稿子&#xff0c;一起饭后散步&am…

php的array_merge函数

array_merge函数用于把一个或多个数组合并为一个数组 语法&#xff1a; array_merge(array1,array2,array3...)<?phpheader(content-type:text/html;charsetutf-8);$a1array("a">"red","b">"green");$a2array("c"…

php 命令链模式,设计模式之------命令链模式

/*****命令链模式&#xff1a;松散耦合为主题&#xff0c;发送消息&#xff0c;命令和请求通过一组命令**封装一系列操作** 一条命令被看做只执行了一个函数********/Interface ICommand{function isValue($val);}class CommonClain{private $_command;public function __const…

[Project Euler] 来做欧拉项目练习题吧: 题目017

[Project Euler] 来做欧拉项目练习题吧: 题目017周银辉题目描述:If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 3 5 4 4 19 letters used in total.If all the numbers from 1 to 1000 (one thousand) inclusive were …

dlf packet_DLF的完整形式是什么?

dlf packetDLF&#xff1a;德里土地和金融 (DLF: Delhi Land and Finance) DLF is an abbreviation of Delhi Land and Finance. Delhi Land and Finance is one of the leading commercial real estate developers in India. In 1946, the company was established by Chaudha…

python求三个数中最小(大)的元素

求最小&#xff1a; def getThreeNumberMin(x,y,z):minx if x<y else yminmin if min<z else zreturn min agetThreeNumberMin(3,-1,-1) print(a)结果&#xff1a; 求最大&#xff1a; def getThreeNumberMin(x,y,z):maxx if x>y else ymaxmax if max>z else zr…

java内存分配空间大小,JVM内存模型及内存分配过程

一、JVM内存模型JVM主要管理两种类型内存&#xff1a;堆(Heap)和非堆(Permanent区域)。1、Heap是运行时数据区域&#xff0c;所有类实例和数组的内存均从此处分配。Heap区分两大块&#xff0c;一块是 Young Generation&#xff0c;另一块是Old Generation&#xff1a;1)在Young…

[Python]Pydev中使用中文

Pydev中默认无法使用中文&#xff0c;注释也不行。 这时需要给文件加一个编码 #-*- coding: utf8 -放在文件的头部 则可以正常使用中文。也可以换成其他的编码。转载于:https://www.cnblogs.com/young40/archive/2011/03/07/1974556.html

python自动翻译pdf_在Python中自动执行PDF

python自动翻译pdfModules used: 使用的模块&#xff1a; In this script, we will use PyPDF2 module which will provide us various functions such as to extract the data and read the pdf file and split the file and write a new file. 在此脚本中&#xff0c;我们将…

设置DVWA出现Could not connect to the MySQL service. Please check the config的解决方法,默认登录账号

按照这个路径&#xff0c;找到config.inc.php文件&#xff0c;打开 找到下面三个语句 db_server:一般填127.0.0.1&#xff0c;如果修改了mysql的端口号&#xff0c;要在后面加上修改后的端口号&#xff0c;默认为3306 db_user:自己mysql数据库的用户名 db_password&#xff1…

java解析excel的js页面,Java导入Excel文件页面实现JS

Excel导入&#xff1a;页面创建导入按钮&#xff0c;如&#xff1a;代码&#xff1a;导入交易JS&#xff1a;function upload(){layer.open({type : 2, //层类型title :导入文件, //标题shadeClose : true,//是否点击遮罩关闭shade : [ 0.4, #000 ], //遮罩maxmin : false, //开…

详谈asp生成静态页方法

生成静态页的好处不用说&#xff0c;当今大型网站&#xff0c;为缓解服务器端的压力许的的页面都改用了静态的页面&#xff0c;并利用AJAX技术动态地更新其中的部分内容&#xff0c;如广告等。一个简单的不用模板可以直接生成HTML静态页的方法. 如一个正常的index.asp动态页面&…

模糊逻辑系统_在模糊逻辑系统中工作 人工智能

模糊逻辑系统As discussed earlier, the Fuzzy Logic System consists of 4 components: the Knowledge Base, Fuzzification Module, Inference Engine, and the Defuzzification Module. We know how the data and information flow between these components, but we do not…

关于用户角色权限的一点想法(1) 选择自 biggie 的 Blog

原文&#xff08;http://dev.csdn.net/article/19/19751.shtm&#xff09; 前言&#xff1a;权限往往是一个极其复杂的问题&#xff0c;但也可简单表述为这样的逻辑表达式&#xff1a;判断“Who对What(Which)进行How的操作”的逻辑表达式是否为真。针对不同的应用&#xff0c;需…

使用anconada 的conda更换环境

打开命令行界面。cmd&#xff0c;直接打开 查看有些环境 conda env list 我这里有两个环境使用指定的环境 我这里就用py27 命令&#xff1a;activate环境名 py27在前面&#xff0c;已经成功更换了退出使用某个环境 conda deactivate 前面已经没有py27&#xff0c;表示已经退…

php采集分页数据,如何通过php+wordpress实现分页获取数据

1.首先我们通过WordPress来搭建我们的博客网站&#xff0c;需要实现分页获取数据&#xff0c;我们需要了解一下WordPress给我们提供的api。主要是get_posts()这个api的使用方法。函数的结构大概长这么个样子&#xff1a;<?php get_posts($args); ?> &#xff0c;其中…

离散结构和离散数学中文书_在离散数学中对场景执行的操作

离散结构和离散数学中文书Prerequisite: Set theory and types of set in Discrete Mathematics 先决条件&#xff1a; 离散数学中的集合论和集合类型 集的基数 (Cardinality of set) It is the number of elements in a set denoted like, A {1, 2, 3, 4} 它是集合中元素的数…