题目:报告系统状态的连续日期
系统 每天 运行一个任务。每个任务都独立于先前的任务。任务的状态可以是失败或是成功。
编写一个 SQL 查询 2019-01-01 到 2019-12-31 期间任务连续同状态 period_state 的起止日期(start_date 和 end_date)。即如果任务失败了,就是失败状态的起止日期,如果任务成功了,就是成功状态的起止日期。
最后结果按照起始日期 start_date 排序。
Failed table | Succeeded table |
---|---|
最后答案要求:
题目理解:
题目意思不太好理解,数据是2018-12-28到2019-01-06 每天都有一个任务失败或者成功。一般情况下的记录方法是“日期+成功/失败”。
题中是将日期根据任务状态分别放到两个表中:成功的记录到Succeeded table里,失败的记录到Failed table。
解法一:窗口函数分组
解题思路:
1)使用UNION all 将两个表连接在一起,
2)用窗口函数和subdate()来找到分组指标diff。SUBDATE()函数从日期中减去时间/日期间隔,然后返回日期。
3)使用group by 根据type和diff再次分组,用min和max找出起始日期。
select type as period_state, min(date) as start_date, max(date) as end_date
from
(
select type, date, subdate(date,row_number()over(partition by type order by date)) as diff
from
(
select 'failed' as type, fail_date as date from Failed
union all
select 'succeeded' as type, success_date as date from Succeeded
) a
)a
where date between '2019-01-01' and '2019-12-31'
group by type,diff
order by start_date
解法二:变量方法
解题思路:
1)两表聚合
2)通过变量给连续状态分组
3)返回需求
# Write your MySQL query statement below
--3、返回需求
SELECT period_state, MIN(date) AS start_date, MAX(date) AS end_date
FROM
--2、通过变量给连续状态分组
(SELECT date, period_state, IF(@pre_state=period_state, @id, @id:=@id+1) AS id, @pre_state:=period_state
FROM
--1、两表聚合
(SELECT fail_date AS date, 'failed' AS period_state
FROM Failed
UNION ALL
SELECT success_date AS date, 'succeeded' AS period_state
FROM Succeeded) A, (SELECT @pre_state:=NULL, @id:=0) B
WHERE date BETWEEN '2019-01-01' AND '2019-12-31'
ORDER BY date) C
GROUP BY id
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/report-contiguous-dates
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。