SQLServer 12 - need asssistance with sqlstmt

Need assistance in creating a SQL statement for SQLServer 2012 –

Table BILLING – main fields in queston: ID,TranDate,Status  

ID      Trandate      Status
1      1/1/2017      P
1      1/1/2017      P
1      1/1/2017      P
1      2/1/2017      O
1      2/1/2017      P
1      2/1/2017      P
1      3/1/2017      P
1      4/1/2017      O
2      1/1/2017      O
(Note BILLING does have a unique index for ID/Trandate/Linenbr – but linenbr does not play a part in the sqlstmt)

Issue: For ID #1 need to return the earliest trandate from BILLING that is >= @trandate where all status for that trandate = ‘P’

For example:
select  min(trandate) from Billing where
id = ‘1’
and   trandate >= ‘@trandate                         (@trandate = 1/1/17)
and status = ‘P’

here’s the issue –
only want  1/1/2017 to be returned if all statuses for 1/1/2017 = ‘P’ (For trandate 1/1/17 that would be true)

But if @trandate = ‘2/1/2017’  would not be true.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornSQL Server Data DudeCommented:
Give this a whirl..
Line 3 allows you to conditionally COUNT based on a value, which can be compared to the overall COUNT
;WITH cte AS (
	SELECT ID, Trandate, 
	  SUM(CASE WHEN Status='P' THEN 1 ELSE 0 END) AS status_p_count, 
	  COUNT(Status) AS status_count
	FROM YourTable
	GROUP BY ID, Trandate) 
SELECT ID, Trandate
FROM cte
WHERE status_p_count = status_count

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.