I’m looking at ways of creating contingency tables in SQL Server 2008. They don’t necessarily have to appear in the 2×2 typical matrix. I’d just like to know if anyone out there can see a better solution than mine.

Please refer to the picture for clarity. The red letters are names of the squares for simplicity’s sake. The label X+ means X is present in that cell and the opposite is true as well.
I will label my queries with the letter of box in the table that they represent
A
select count(*) from
(
select distinct p.patientid
from Patient as p
inner join icdpatient as picd on picd.patientid = p.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.icdText like '%x%'
) as t
inner join
(
select distinct p.patientid
from Patient as p
inner join icdpatient as picd on picd.patientid = p.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.icdText like '%y%'
) as s on s.patientid=t.patientid
B
select count(*) from
(
select distinct p.patientid
from Patient as p
inner join icdpatient as picd on picd.patientid = p.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.icdText like '%x%'
) as t
left join
(
select distinct p.patientid
from Patient as p
inner join icdpatient as picd on picd.patientid = p.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.icdText like '%y%'
) as s on s.patientid=t.patientid
where s.patientid is null
C
select * from
(
select distinct p.patientid
from Patient as p
inner join icdpatient as picd on picd.patientid = p.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.icdText like '%x%'
) as t
right join
(
select distinct p.patientid
from Patient as p
inner join icdpatient as picd on picd.patientid = p.patientid
and picd.admissiondate = p.admissiondate
and picd.dischargedate = p.dischargedate
inner join tblicd as t on t.icd_id = picd.icd_id
where t.icdText like '%y%'
) as s on s.patientid=t.patientid
where t.patientid is null
D
This one I’m a little iffy about but I think I’m going to do something like
declare @d int
set @d = (select count(distinct p.patientid) from Patient as p) - b -c
This aims to find the entire population and subtracting those ONLY with X and ONLY with y
Yes! There are easier ways. Assuming your join produces no duplicate patients:
Otherwise replace the count(*) with:
This should give you the information you need for the contingency table.