SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How To Take Count Of Id's
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

taj
Starting Member

India
39 Posts

Posted - 09/07/2013 :  02:02:13  Show Profile  Reply with Quote
Hi All,

I have a table Patient_Lab_Tests as shown below:

PATIENT_ID TEST_CODE REPORT_GENERATED
101 6 Y
101 12 Y
101 15 N
102 6 Y
102 12 Y
102 15 Y
103 6 Y
103 12 Y


REQUIREMENT:

I want to show the count of Patient_id 's for which the Report_Generated column is 'Y'

Output Result:
Patient_Count
2

My Result is only 2 because for PATIENT_ID's 102 & 103 the REPORT_GENERATED Columns is 'Y' for all tests.So PATIENT_ID 101 is not consider in my count since one of the test_code for patient_id 101 is 'N' in REPORT_GENERATED column.

How to do this using sql server?

Thank You,

khtan
In (Som, Ni, Yak)

Singapore
17584 Posts

Posted - 09/07/2013 :  03:14:09  Show Profile  Reply with Quote
select	count(*)
from
(
	select	PATIENT_ID
	from	yourtable
	group by PATIENT_ID
	having min(REPORT_GENERATED) = 'Y'
) d



KH
Time is always against us

Go to Top of Page

bitsmed
Constraint Violating Yak Guru

319 Posts

Posted - 09/07/2013 :  03:24:02  Show Profile  Reply with Quote
Alternative:

with patient_lab_tests (patient_id,test_code,report_generated)
  as (          select 101,6,'Y'
      union all select 101,12,'Y'
      union all select 101,15,'N'
      union all select 102,6,'Y'
      union all select 102,12,'Y'
      union all select 102,15,'Y'
      union all select 103,6,'Y'
      union all select 103,12,'Y'
     )
select count(*) as patient_count
  from (select patient_id
          from patient_lab_tests
         group by patient_id
         having avg(case when report_generated='Y' then 1 else 0 end)=1
       ) as a
Go to Top of Page

madhivanan
Premature Yak Congratulator

India
22744 Posts

Posted - 09/08/2013 :  04:33:18  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
select count(*)
from
(
	select	PATIENT_ID
	from	yourtable
	group by PATIENT_ID
	having min(REPORT_GENERATED) = 'Y' and max(REPORT_GENERATED) = 'Y'
) d

Also refer this to know how you can use HAVING clause for various purposes http://beyondrelational.com/modules/2/blogs/70/posts/19573/efficient-filtering-with-having-clause.aspx

Madhivanan

Failing to plan is Planning to fail

Edited by - madhivanan on 09/08/2013 04:33:54
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.07 seconds. Powered By: Snitz Forums 2000