Sql 重复orderid时如何删除记录

Sql 重复orderid时如何删除记录,sql,sql-server,Sql,Sql Server,预期产出 OrderId InvoiceNumber LocationId 1 A1 1 1 B1 2 1 0 2 0 3 C1 2 3 0 在上面的结果中…我想删除当orderId在查询中重复时,InvoiceNumbe

预期产出

OrderId   InvoiceNumber  LocationId
1          A1             1
1          B1             2
1                         0
2                         0
3          C1             2
3                         0
在上面的结果中…我想删除当orderId在查询中重复时,InvoiceNumber为null且LocationId为0的记录

在上面的示例中,…OrderId=1记录被重复,因此检查InvoiceNuber为null,LocationId为0(如果找到),然后将其删除

OrderId=2不重复,因此保留记录

我试过这个

OrderId   InvoiceNumber  LocationId
1          A1             1
1          B1             2
2                         0
3          C1             2
但是…这个问题是错误的


谢谢你

您可以使用窗口功能:

Select * from tblName where isnull(InvoiceNuber,'')='' and LocationId=0

这将逐出
InvoiceNumber
null
locationId
0
的行,其中另一行存在相同的
orderId
且非
null
InvoiceNumber
是否应考虑间隙?只有当记录彼此相邻对齐,或者结果集中的任何地方也会是重复的,它才被视为重复序列吗?@Akhilessingh:对不起,在
where
子句中缺少了一个周围的
not
。修正了。先生,它显示了所有的REOCRD…。不是预期的输出。@AkhileshSingh:对于您的样本数据,这会产生您显示的结果,正如您所看到的。先生,如果我们使用空格(“”)而不是空值…它会显示完全不同的结果…@AkhileshSingh:当然,如果您更改样本数据,结果是不同的。。。如果需要空格而不是
null
s,请在
where
子句中使用
InvoiceNumber='
而不是
InvoiceNumber is null
select *
from (
    select t.*, count(InvoiceNumber) over(partition by orderId) cnt
    from mytable t
) t
where not (InvoiceNumber is null and locationId = 0 and cnt > 0)