我有一张桌子:
Date Msg
2019-04-11 10:14:02.773 AB123 <this is Succec bec next line is CD
2019-04-11 10:14:02.647 CD123
2019-04-11 10:11:03.670 AB123
2019-04-11 10:11:03.500 CD123
2019-04-10 09:53:39.743 AB123 <this is fail bec next line is not CD
2019-04-10 09:52:39.743 AB123
2019-04-10 09:53:39.743 CD123
2019-04-10 09:52:39.743 AB123 <this is fail bec next line is not CD
2019-04-10 09:52:39.743 AB123 <this is fail bec next line is NULL
我想找到Msg的前2行AB,而CD是成功的ORDER BY Date
如果具有AB的消息继续出现,将失败,直到CD 1套
CREATE TABLE table1 (
`Id` INTEGER,
`Date` DATETIME,
`Msg` VARCHAR(5)
);
INSERT INTO table1
(`Id`, `Date`, `Msg`)
VALUES
('1', '2019-04-11 10:14:02.773', 'AB123'),
('2', '2019-04-11 10:14:02.647', 'CD123'),
('3', '2019-04-11 10:11:03.670', 'AB123'),
('4', '2019-04-11 10:11:03.500', 'CD123'),
('5', '2019-04-10 09:53:39.743', 'AB123'),
('6', '2019-04-09 09:53:39.587', 'AB123'),
('7', '2019-04-09 09:53:39.001', 'CD123'),
('8', '2019-04-08 07:53:39.587', 'AB123'),
('9', '2019-04-07 08:53:39.111', 'AB123');
SELECT t.Id, t.Date, t.Msg
FROM ( SELECT Id, Date, Msg, LEAD(Msg) OVER (ORDER BY Date DESC) AS NextMsg FROM table1 ) t
WHERE t.Msg LIKE '%AB%' AND t.NextMsg LIKE '%AB%'
ORDER BY t.Date DESC
我的预期输出是
Id Date Msg Check
5 2019-04-10 09:53:40 AB123 fail
8 2019-04-08 07:53:40 AB123 fail
9 2019-04-07 08:53:39 AB123 fail
答案 0 :(得分:0)
如果我猜你想要的是什么,它将起作用:
select a.*,case when regexp_like(a.Msg,'(.)*AB(.)*')=1 or
regexp_like(a.Msg,'(.)*CD(.)*')=1 then 'IsSuccess'
when regexp_like(a.Msg,'(.)*EF(.)*')=1 then 'IsFail'
else null end status from table1 a
答案 1 :(得分:0)
如果我正确理解了您的问题,并且希望使用当前行和后续行中的值来过滤表,则使用LEAD()的下一种方法可能会有所帮助:
输入
CREATE TABLE #Data (
Id int,
[Date] datetime,
Msg varchar(5)
)
INSERT INTO #Data
(Id, [Date], Msg)
VALUES
(1, '2019-04-11T10:14:02.773', 'AB123'),
(2, '2019-04-11T10:14:02.647', 'CD123'),
(3, '2019-04-11T10:11:03.670', 'AB123'),
(4, '2019-04-11T10:11:03.500', 'CD123'),
(5, '2019-04-10T09:53:39.743', 'AB123'),
(6, '2019-04-10T09:52:39.743', 'AB123')
声明
SELECT t.Id, t.[Date], t.[Msg]
FROM (
SELECT
Id,
[Date],
Msg,
LEAD(Msg) OVER (ORDER BY [Date] DESC) AS NextMsg
FROM #Data
) t
WHERE t.Msg LIKE '%AB%' AND ((t.NextMsg NOT LIKE '%CD%') OR (t.NextMsg IS NULL))
ORDER BY t.[Date] DESC
输出
Id Date Msg
5 10/04/2019 09:53:39 AB123
6 10/04/2019 09:52:39 AB123
答案 2 :(得分:0)
我怀疑您想在某个时间范围内(例如1秒或1分钟)找到没有“ CD”值的“ AB”值。
如果是,请使用not exists
:
选择t。*
从T
其中t.msg如“ AB%”,
不存在(选择1
从t t2
其中t2.msg如“ CD%”和
t2.date