在SQL中,我有一个ID列表及其关联的REC号。我的目标是删除RECNO为0的行,但前提是有另一行的RECNO为非0。
之前:
DLREC# RECNO
3583 | 0
586 | 0
3589 | 0
3589 | 123456789
3609 | 0
3650 | 0
3650 | 451230149
之后:
DLREC# RECNO
3583 | 0
3586 | 0
3589 | 123456789
3609 | 0
3650 | 451230149
答案 0 :(得分:0)
使用示例数据的简单方法是MAX
select
[DLREC#]
,max(RECNO)
from YourTable
group by [DLREC#]
对于SQL Server
如果每个DLREC#
的值都更多,则另一个方法是窗口函数。
with cte as(
select *
,RN = row_number() over (partition by [DLREC#] order by RECNO)
,CT = count(*) over (partition by [DLREC#]))
select
[DLREC#]
,RECNO
from CTE
where (RN != 1 and CT > 1) or (RN = 1 and CT = 1)
答案 1 :(得分:0)
您可以将not exists
与delete
一起使用:
delete t from t
where recno = 0 and
exists (select 1 from t t2 where t2.dlrec = t.dlrec and t2.recno <> 0);