繁体   English   中英

SQL Server:排除表中的行如果有另一行具有相同的col值和特定的二级列值

[英]SQL Server : excluding rows from a table IF there is another row with the same col value and a particular secondary column value

我有一个包含AccountInvoiceID列的表,一个帐户可以有多个InvoiceID行,而我正在尝试添加一个选项,如果有一个具有特定Status的行,它将过滤掉所有帐户行。

对于我的小数据集,我可能有15条记录,3个帐户,每个帐户有5张发票。 如果其中一条记录的Status0我希望这样,其余4条被过滤掉。 我尝试使用EXCEPT来执行此操作,但它只过滤掉了值为0的单行并留下了余数。

我之前只使用过SQL Server的基础知识,所以我很遗憾看到你可以在一个声明中使用的所有更高级的功能,所以我希望有人能指出我正确的方向。 谢谢!

编辑例如数据:

Id  Account  enddate     Status  InvoiceID
0   5000     2011-10-10  1       1
1   5000     2012-10-10  1       2
2   5000     2013-10-10  1       3
3   5000     2014-10-10  1       4
4   5000     2015-10-10  0       5
5   5999     2013-10-10  1       1
6   5999     2014-10-10  1       2
7   5999     2015-10-10  1       3
8   1002     2014-10-10  1       1
9   1002     2015-10-10  1       2

如果我对10月结束的发票运行查询并返回这些结果,我想进一步筛选出帐户5000的所有记录,因为它有一个状态为0的行,并保留帐户5999和1002的记录。

您可以使用not exists子句来过滤掉与状态为0的行具有相同帐号的任何行。下面的内容如下:

select * 
from table1 t1
where not exists (
  select account
  from table1 t2
  where t2.account=t1.account
    and t2.status=0
)

稍有不同的方法是:

select *
from table1 t1
where account not in (
  select distinct account
  from table1 t2
  where t2.status=0 )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM