【SQL】1661. 每台机器的进程平均运行时间 (四种写法;自连接;case when;窗口函数lead();)

前述

Sql窗口分析函数【lead、lag详解】
Hive 分析函数lead、lag实例应用

  • lag :用于统计窗口内往上第n行值
  • lead :用于统计窗口内往下第n行值
sql 复制代码
lead(列名,1,0) over (partition by 分组列 order by 排序列 rows between 开始位置 preceding and 结束位置 following)

lag 和lead 有三个参数:

  1. 列名;
  2. 偏移的offset;
  3. 超出记录窗口时的默认值。

题目描述

leetcode题目:1661. 每台机器的进程平均运行时间


Code

写法一:自连接

sql 复制代码
select A.machine_id,
    round(avg(B.timestamp - A.timestamp), 3) as processing_time
from Activity A, Activity B 
where A.machine_id = B.machine_id and
    A.process_id = B.process_id and 
    A.activity_type = 'start' and
    B.activity_type = 'end'
group by machine_id

过程解析:连表,然后过滤需要的行。

写法二:同组内最大最小值确定end time和start time

思路转换:同组内的结束时间-开始时间 == max(timestamp) - min(timestamp)

sql 复制代码
select machine_id,
    round(avg(timm), 3) as processing_time 
from (
    select *,
        max(timestamp) - min(timestamp) as timm 
    from Activity
    group by machine_id, process_id
) A 
group by machine_id

写法三:case when

思路:把 end 时间变成负数,方便求和/平均值计算。

sql 复制代码
select machine_id,
    round(avg(timm)*2, 3) as processing_time
from (
    select *,
        case 
            when activity_type='end' 
            then timestamp 
            else -timestamp
        end as timm
    from Activity
) A 
group by machine_id

过程解析:

写法四:窗口函数lead()

sql 复制代码
with t as(
    select *, 
        lead(timestamp, 1, 0) over(partition by machine_id order by process_id asc, timestamp asc) as end_time
    from Activity
)
select t.machine_id,
    round(avg(end_time-timestamp), 3) as processing_time
from t 
where t.activity_type = 'start'
group by t.machine_id


此写法学习大佬的题解 WITH+LEAD窗口函数

相关推荐
mr_LuoWei20092 分钟前
python工具:python代码知识库笔记
数据库·python
这周也會开心12 分钟前
Redis数据类型的底层实现和数据持久化
数据库·redis·缓存
ん贤13 分钟前
一次批量删除引发的死锁,最终我选择不加锁
数据库·安全·go·死锁
im_AMBER20 分钟前
Leetcode 114 链表中的下一个更大节点 | 删除排序链表中的重复元素 II
算法·leetcode
数据知道23 分钟前
PostgreSQL 核心原理:系统内部的对象寻址机制(OID 对象标识符)
数据库·postgresql
历程里程碑36 分钟前
普通数组----轮转数组
java·数据结构·c++·算法·spring·leetcode·eclipse
pp起床37 分钟前
贪心算法 | part02
算法·leetcode·贪心算法
sin_hielo37 分钟前
leetcode 1653
数据结构·算法·leetcode
YuTaoShao1 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法二)排序 + 二分查找
数据结构·算法·leetcode
Q741_1471 小时前
C++ 优先级队列 大小堆 模拟 力扣 703. 数据流中的第 K 大元素 每日一题
c++·算法·leetcode·优先级队列·