简体   繁体   中英

Need to count certain rows based on date criteria in SQL Server

I'm using SQL Server 2012 and have a table with these 2 columns. I need to count an ORG_ID once ONLY IF the EndDate for every row or that ORG_ID falls within/before the timeframe of '1-1-2018' and '1-31-2018' (or before but NOT after) for ALL rows for that org. An ORE with an EndDate of NULL would also NOT be in my results

ORG_ID              EndDate    
99968042            1/31/2018    
99968042            2/14/2018    
99968042            2/14/2018    
99900699            1/10/2018    
99900699            1/10/2018    
99900699            1/10/2018    
99900699            1/10/2018    
99899776            1/20/2018    
99843366           12/17/2017    
99843366             1/4/2018    
99841000             2/1/2016    
99651255             NULL
99651255             1/15/2018

The rows that should output are:

99900699    
99899776    
99843366    

I haven't tried anything, because I can't think how to approach it.

So now I've tried this:

select distinct ORG_ID
from ##PLCMT p1
where not exists (
    select *
    from ##PLCMT p2
    where p1.ORG_ID = p2.ORG_ID and
          (p1.EndDate <= '2018-01-01' or p1.enddate >= '2018-01-31' or p1.EndDate is NULL)
   )  

and it is still resulting back an org that has a NULL enddate, I can't figure out why. ORG_ID 3098376 is in my results but if I look at all the rows for that ORG_ID, it looks like this:

select *
from ##PLCMT
where org_id = '3098376'  

results:
ORG_ID EndDate
3098376 2017-09-11
3098376 NULL
3098376 NULL

Use group by and having and NOT IN (to eliminate those who have any NULL value):

SELECT org_id
FROM t
GROUP BY org_id
WHERE org_id NOT IN (SELECT org_id FROM t WHERE enddate IS NULL)
HAVING MAX(enddate) <= '2018-01-31';

Your are probably safe with this logic:

having max(enddate) < '2018-02-01'

This works even if enddate has a time component.

Another way is with NOT EXISTS()

SELECT DISTINCT org_id
from t
WHERE NOT EXISTS(
  SELECT * FROM t t1
  WHERE t1.org_id=t.org_id
  AND (t1.enddate > '20180131' OR t1.enddate IS NULL)
)

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.

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