I have a single table with columns for Account
and InvoiceID
, an account can have multiple InvoiceID
rows and I'm trying to add an option that will filter out ALL account rows if there is a row that has a particular Status
.
For my small data set I might have 15 records, 3 accounts each having 5 invoices. If one of those records has a Status
of 0
I would like that and the remaining 4 to be filtered out. I tried using EXCEPT
to do this but it only filtered out the single row with the value of 0 and left the remainders.
I've only worked with the basics of SQL Server before so I'm feeling quite lost looking at all the more advanced features you can use in a statement so I was hoping someone could point me in the right direction. Thanks!
Edit for example data:
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
If I run a query for invoices that end in october and come back with these results, I want to further filter out ALL records of Account 5000 because it has a row with a status of 0 and leave the records for accounts 5999 and 1002.
You could use a not exists
clause, to filter out any rows that have the same account number as a row with status 0. Something along the lines of the following:
select *
from table1 t1
where not exists (
select account
from table1 t2
where t2.account=t1.account
and t2.status=0
)
A slightly different approach would be:
select *
from table1 t1
where account not in (
select distinct account
from table1 t2
where t2.status=0 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.