我有一个表,其中有所有ID,第二个表中有ID,该进程中有错误。我需要查询选择错误发生之前的最后3个ID。 例如:
first table:
id | info
___________________
100 | 1.0
101 | 2.0
102 | 6.0
103 | 9.0
104 | 15.0
105 | 8.0
106 | 6.0
107 | 8.0
108 | 6.0
109 | 8.0
110 | 6.0
id of errors:
id
____
104
110
因此,此查询将必须返回ID的值: 109,108,107,103,102和101
预先感谢
答案 0 :(得分:4)
SELECT result.*
FROM errors e
CROSS APPLY (
SELECT TOP 3 *
FROM [first table] ft
WHERE ft.id < e.id
ORDER BY ft.id DESC
) result
答案 1 :(得分:1)
这可能对您有用:
设置:
Create Table #Errs
(
Id Int
);
Insert Into #Errs Values
(104), (110)
Create Table #tbl
(
Id Int,
Info Decimal(6,2)
);
Insert Into #tbl Values
(100,1.0),
(101,2.0),
(102,6.0),
(103,9.0),
(104,15.0),
(105,8.0),
(106,6.0),
(107,8.0),
(108,6.0),
(109,8.0),
(110,6.0)
查询
With cte As
(
Select
Id,
LAG(Id,1,Null) OVER(Order By Id) As iderror1,
LAG(Id,2,Null) OVER(Order By Id) As iderror2,
LAG(Id,3,Null) OVER(Order By Id) As iderror3
From #tbl t
)
Select iderror1 As ErrorList From cte Where Id In (Select Id From #Errs)
Union ALL
Select iderror2 As ErrorList From cte Where Id In (Select Id From #Errs)
Union ALL
Select iderror3 As ErrorList From cte Where Id In (Select Id From #Errs)
Order By ErrorList
如果您的ID不是按顺序排列的,则可以使用(选择NULL),如下所示:
With cte As
(
Select
Id,
LAG(Id,1,Null) OVER(Order By (Select NULL)) As iderror1,
LAG(Id,2,Null) OVER(Order By (Select NULL)) As iderror2,
LAG(Id,3,Null) OVER(Order By (Select NULL)) As iderror3
From #tbl t
)
Select iderror1 As ErrorList From cte Where Id In (Select Id From #Errs)
Union ALL
Select iderror2 As ErrorList From cte Where Id In (Select Id From #Errs)
Union ALL
Select iderror3 As ErrorList From cte Where Id In (Select Id From #Errs)
Order By ErrorList
结果
ErrorList
--------
101
102
103
107
108
109
答案 2 :(得分:0)
您可以使用窗口函数来计算助手组SUM()
和ROW_NUMBER()
以获得最后3行:
WITH cte AS (
SELECT t1.*, -sub.c+ SUM(sub.c) OVER(ORDER BY t1.id) AS grp
FROM t1
LEFT JOIN t2
ON t1.id = t2.id
CROSS APPLY (SELECT CASE WHEN t2.id IS NULL THEN 0 ELSE 1 END) sub(c)
), cte2 AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY grp ORDER BY id DESC) rn
FROM cte
)
SELECT id, info
FROM cte2
WHERE rn BETWEEN 2 AND 4
ORDER BY id;