力扣题目跳转(613. 直线上的最近距离 - 力扣(LeetCode))
表:
Point
+-------------+------+ | Column Name | Type | +-------------+------+ | x | int | +-------------+------+ 在SQL中,x是该表的主键列。 该表的每一行表示X轴上一个点的位置。
题目要求:
找到 Point
表中任意两点之间的最短距离。
返回结果格式如下例所示。
示例 1:
输入: Point 表: +----+ | x | +----+ | -1 | | 0 | | 2 | +----+ 输出: +----------+ | shortest | +----------+ | 1 | +----------+ 解释:点 -1 和 0 之间的最短距离为 |(-1) - 0| = 1。
case 1 的建表语句。
Create Table If Not Exists Point (x int not null)
Truncate table Point
insert into Point (x) values ('-1')
insert into Point (x) values ('0')
insert into Point (x) values ('2')
一 首先,我们把所有的距离求出来。
select abs(p1.x - p2.x) as top from Point p1,Point p2 where p1.x != p2.x;
输出如下
二 然后选出最短的那个,使用 distinct 去重。
with tmp as( select abs(p1.x - p2.x) as top from Point p1,Point p2 where p1.x != p2.x ) select min(top) as shortest from tmp;
输出如下
以上就是全部答案,如果对你有帮助请点个赞,谢谢。
来源:力扣(leecode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
转载请注明出处:
我会尽快把力扣上的所有数据库题目发出来。感兴趣的可以点个赞与关注。每天不定时跟新。