Sql 删除除特定值和下两行之外的所有内容
我需要帮助,以删除使用SQL语句,我可以删除一切,除了值包含'开始'对 Value1字段和下面包含Keep*值的下两行。记住Keep*值也可以是其他不同的值,我只是以Keep为例 谢谢Sql 删除除特定值和下两行之外的所有内容,sql,sql-server,sql-server-2017,Sql,Sql Server,Sql Server 2017,我需要帮助,以删除使用SQL语句,我可以删除一切,除了值包含'开始'对 Value1字段和下面包含Keep*值的下两行。记住Keep*值也可以是其他不同的值,我只是以Keep为例 谢谢 **ID DocumentName Value1 Value2** __ ____________ ______ _____ 1 Doc1 AB 123rt 2 Doc1 CD 4543 3
**ID DocumentName Value1 Value2**
__ ____________ ______ _____
1 Doc1 AB 123rt
2 Doc1 CD 4543
3 Doc1 CE fgf
4 Doc1 Csafsaf fghfdg
5 Doc1 sdsaff sdsa
6 Doc1 Start From
7 Doc1 Keep2 Stay2
8 Doc1 Keep3 Stay3
9 Doc1 Stop end
10 Doc1 hjkhjkiu iuoiuio
11 Doc1 zxzfd bxgx
12 Doc2 AB 123rt
13 Doc2 CD 4543
14 Doc2 CE fgf
15 Doc2 Csafsaf fghfdg
16 Doc2 sdsaff sdsa
17 Doc2 Start From
18 Doc2 Keep5 Stay5
19 Doc2 Keep6 Stay6
20 Doc2 Stop end
21 Doc2 hjkhjkiu iuoiuio
22 Doc2 zxzfd bxgx
23 Doc3 dds gdgd
24 Doc3 jhkjh jhjkh
25 Doc3 jkkjh fgf
26 Doc3 hnmnbjkhjkiu mnbmn
27 Doc3 nmb nbmn
28 Doc3 Start From
29 Doc3 Keep7 Stay7
30 Doc3 Keep8 Stay8
31 Doc3 Stop end
基本上,我想知道这些值
**ID DocumentName Value1 Value2**
__ ____________ ______ _____
6 Doc1 Start From
7 Doc1 Keep2 Stay2
8 Doc1 Keep3 Stay3
17 Doc2 Start From
18 Doc2 Keep5 Stay5
19 Doc2 Keep6 Stay6
28 Doc3 Start From
29 Doc3 Keep7 Stay7
30 Doc3 Keep8 Stay8
如果
id
s没有间隙,您可以执行以下操作:
delete from t
where (select t2.id
from t t2
where t2.documentname = t.documentname and
t2.value = 'Start'
) not in (t.id, t.id + 1, t.id + 2) and
(t.value = 'Start' or t.value like 'Keep%')
关键的是,这假设每个文档只有一个起始行,并且
id
中没有间隙使用CTE
和lag()
窗口函数:
with cte as (
select *,
lag(Value1, 1) over (partition by DocumentName order by ID) prev1,
lag(Value1, 2) over (partition by DocumentName order by ID) prev2
from tablename
)
delete from cte
where 'Start' not in (Value1, coalesce(prev1, ''), coalesce(prev2, ''))
请参阅。结果:
如果没有两行“keep”呢?同时标记您正在使用的数据库。请使用您正在使用的数据库标记您的问题:mysql、sql server、postgresql…?这是Mircrosoft sql 2017上的。谢谢。您想在
开始
之后的任何两行,还是只要它们包含某个文本(在您的示例中保留*
)嗨,Gordan,谢谢您的帮助。您的语法中有2个错误。上的最后两行)不在(t.id,t.id+1,t.id+2)和(t2.value='Start'或t2.value,如'Keep%')中。value不在子查询表gordan,Tks中,请提供帮助。您的语法中有2个错误。你能提出建议吗?上的最后两行)不在(t.id,t.id+1,t.id+2)和(t2.value='Start'或t2.value,如'Keep%')中,并且t2.value不在子查询表中。我得到一个错误消息4104,16级,状态1,第53行多部分标识符“t.id”无法绑定。Msg 4104,级别16,状态1,第54行无法绑定多部分标识符“t2.Col1”。请将其恢复为上一行已打开)不在(t.id,t.id+1,t.id+2)中,并且除最后一行外正在工作。另外,我将最后一行t2.value更改为t1.value,我遇到了另一个错误msg512,级别16,状态1,第45行子查询返回了多个值。当子查询在=、!=、=或者当子查询用作表达式时。谢谢。你支持它。
> ID | DocumentName | Value1 | Value2
> -: | :----------- | :----- | :-----
> 6 | Doc1 | Start | From
> 7 | Doc1 | Keep2 | Stay2
> 8 | Doc1 | Keep3 | Stay3
> 17 | Doc2 | Start | From
> 18 | Doc2 | Keep5 | Stay5
> 19 | Doc2 | Keep6 | Stay6
> 28 | Doc3 | Start | From
> 29 | Doc3 | Keep7 | Stay7
> 30 | Doc3 | Keep8 | Stay8