选择在<x days =“”

时间:2019-01-25 05:02:19

标签: mysql sql

=“”

时间段内继续重复出现的数据。

KEY     |ERRRTYPE       |CREATEDATE |ERROR  
101aa   |Not on Target  |1/2/2019   |Y
111bw   |Not on Target  |1/2/2019   |Y
123ds   |Not on Target  |1/2/2019   |Y
101aa   |Not on Target  |1/3/2019   |Y
121kd   |Not on Target  |1/3/2019   |Y
111bw   |Not on Target  |1/3/2019   |Y
132ee   |Not on Target  |1/4/2019   |Y
123ww   |Not on Target  |1/4/2019   |Y
111bw   |Not on Target  |1/4/2019   |Y
123kk   |Not on Target  |1/4/2019   |Y
111bw   |Not on Target  |1/5/2019   |Y
101aa   |Not on Target  |1/5/2019   |Y
234ew   |Not on Target  |1/5/2019   |Y
111bw   |Not on Target  |1/6/2019   |Y
101aa   |Not on Target  |1/6/2019   |Y
124dd   |Not on Target  |1/6/2019   |Y

我需要找到当前或最新日期记录的下拉列表,以及过去5天或更短时间内连续重复出现的KEY字段,然后需要在新列中返回Y,

以下数据应如下所示:

KEY     |ERRRTYPE       |CREATEDATE     |ERROR  |Consecutive 
111bw   |Not on Target  |1/6/2019       |Y      | Y           
101aa   |Not on Target  |1/6/2019       |Y      | Y
124dd   |Not on Target  |1/6/2019       |Y      | N

由于KEYs = 111bw每天连续重复5次,并且密钥101aa连续重复2次,因此,连续错误字段的Y应该是N,否则是N

2 个答案:

答案 0 :(得分:0)

以下解决方案是在SQL Server上准备的 我不确定它是否可以在MySQL上成功运行 由于所有功能都是标准的SQL,例如dense_rank,CTE等,因此,我希望有一种方法可以将跟随代码转换为MySQL代码,或者按原样工作

;with cte as (
    select
    *, dense_rank() over (order by createdate desc) rn
    from ErrorData
)
select
    [KEY], ERRRTYPE, CREATEDATE, ERROR,
case when t.cnt = 5 then 'Y' else 'N' end as Consecutive 
from cte
cross apply (
    select
    count(*) as cnt
    from ErrorData e
    where e.[KEY] = cte.[KEY]
    and e.createdate >= dateadd(dd, -5, cte.createdate)
) as t
where rn = 1

enter image description here

答案 1 :(得分:0)

一天中每把钥匙的频率是多少?该密钥可以重复一天中的次数,也可以一天重复一次