There are a couple of ways you can do this...
This query will get the number of dtl_status for each batch_name
SELECT Batch_Name, DTL_Status, Count(*) as NIcount from invoices
where DTL_Status = 'NI'
group by Batch_Name, DTL_Status
and this one will get the total number of invoices per batch_name
SELECT Batch_Name, Count(*) as AllCount from invoices
group by Batch_Name
You can combine these two queries (I'm using two Common Table Expressions below - see
CTE In SQL Server[
^]), and join back to your Batches table to get the rest of the data when the count of NI status is the same as the total number of invoices...
;with t1 as (
SELECT Batch_Name, DTL_Status, Count(*) as NIcount from invoices
where DTL_Status = 'NI'
group by Batch_Name, DTL_Status
)
, t2 as (SELECT Batch_Name, Count(*) as AllCount from invoices
group by Batch_Name)
select b.Batch_Name, b.Scan_Folder
from t1
join t2 on t1.Batch_Name = t2.Batch_Name
join batches b on t1.Batch_Name = b.Batch_Name
where t1.NICount = t2.AllCount
This can be done even more neatly (if you have SQL Server 2005 or later) by using the
OVER[
^] clause like this
;with temp as
(
Select Distinct Batch_Name, Count(*) OVER(PARTITION BY Batch_Name) AS Total
, count(*) OVER(PARTITION BY Batch_Name, DTL_Status) AS NIStatus
from invoices
)
SELECT b.*
FROM batches b
join temp on b.Batch_Name = temp.Batch_Name
where Total = NIStatus