Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

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

Starting Member

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:

101 6 Y
101 12 Y
101 15 N
102 6 Y
102 12 Y
102 15 Y
103 6 Y
103 12 Y


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

Output Result:

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,

In (Som, Ni, Yak)

17689 Posts

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

Time is always against us

Go to Top of Page

Aged Yak Warrior

545 Posts

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

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

Premature Yak Congratulator

22864 Posts

Posted - 09/08/2013 :  04:33:18  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
select count(*)
	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


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  
 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.04 seconds. Powered By: Snitz Forums 2000