我有一张桌子,在桌子上,我有4列
(ID(例如12个不同的ID重复10000行,但随后的10000行增加+26), 日期(以此排序-不能更改-), 错误(-1,0,1), ItemName,
如果我想让我的查询警告我,如果相同的ID彼此紧接有3个错误,该怎么办 (因为整个表按Date排序,所以不确定各行实际上是紧挨着的,例如,ID 1可以位于第一行,然后位于第13行,然后是第25行)?
答案 0 :(得分:0)
根据我的理解,您需要有3个错误且按日期顺序连续的项目。 请参考我的代码和此支持sql server
/*create table*/
CREATE TABLE YourTable( PK_Id int NOT NULL IDENTITY(1,1) primary key,
ID int NOT NULL,
CreatedDate datetime NOT NULL,
Error int NOT NULL,
ItemName nvarchar(100) NULL);
/*sample data 1*/
INSERT INTO YourTable VALUES (1, '2018-10-13 10:10:10', -1, 'Item-1'),
(2, '2018-10-13 10:10:15', -1, 'Item-2'),
(3, '2018-10-13 10:10:17', -1, 'Item-3'),
(4, '2018-10-13 10:10:17', -1, 'Item-4'),
(1, '2018-10-14 10:10:10', 0, 'Item-1'),
(2, '2018-10-14 10:10:15', 0, 'Item-2'),
(3, '2018-10-14 10:10:17', 0, 'Item-3'),
(4, '2018-10-14 10:10:17', 0, 'Item-4'),
(1, '2018-10-15 10:10:10', 1, 'Item-1'),
(2, '2018-10-15 10:10:15', 1, 'Item-2'),
(3, '2018-10-15 10:10:17', 1, 'Item-3'),
(4, '2018-10-15 10:10:17', 1, 'Item-4')
/*sample data 2*/
INSERT INTO YourTable VALUES (5, '2018-10-16 10:10:10', -1, 'Item-5'),
(5, '2018-10-16 10:10:15', 0, 'Item-5'),
(5, '2018-10-16 10:10:17', 1, 'Item-5')
SELECT Id, ItemName
FROM YourTable
GROUP BY Id, ItemName
HAVING COUNT(Error) = 3 /*check number of errors*/
AND SUM(Error) = 0 /*check all 3 errors*/
AND SUM(PK_Id) = MIN(PK_Id) * 3 + 3 /*check right after each error*/
答案 1 :(得分:0)
这应该使您入门;请使用SQL Server 2012+中的LAG()函数确定上一行以及该行之前的值(也许有一种方法可以像我一样在一次而不是两次中完成此操作)。这将返回三个错误序列的最后一行(假设-1是错误代码)。
USE tempdb;
CREATE TABLE Logs (ID int, Dt datetime, error int, itemname varchar(20))
CREATE CLUSTERED INDEX cx ON LOGS (dt)
INSERT INTO LOGS
VALUES (1, '20180101', -1, 'error'),
(1, '20180102', -1, 'error'),
(1, '20180103', -1, 'error'),
(1, '20180104', 0, 'no error'),
(2, '20180102', -1, 'error'),
(2, '20180103', -1, 'error'),
(2, '20180104', 0, 'no error'),
(2, '20180105', -1, 'error')
; with c AS (
SELECT *
, LAG(error, 1,0) OVER (PARTITION BY ID ORDER BY Dt) prv1
, LAG(error, 2,0) OVER (PARTITION BY ID ORDER BY Dt) prv2
FROM Logs
)
SELECT *
FROM c
WHERE error = prv1 and error = prv2
AND error = -1
DROP TABLE Logs