有一个大型数据库,我从中提取了一个研究人群。出于比较的目的,我想选择一个具有相似特征的对照组。我想匹配的两个标准是年龄和性别。为我提供匹配目的的数字的查询是
select sex, age/10 as decades,COUNT(*) as counts
from
(
select distinct m.patid
,m.sex,DATEPART(year,min(c.admitdate)) -m.yrdob as Age
from members as m
inner join claims as c on c.patid=m.PATID
group by m.PATID, m.sex,m.yrdob
)x group by sex, Age/10
结果集看起来像
这个时代的十年列由表达式给出
(DATEPART(year,min(c.admitdate)) -m.yrdob)/10
这用于使用整数除法查找年龄范围为 20-29、30-39 等的人。例如,我想从更大的数据集中选择 507 位 20 多岁的女性。查找较大数据集特征的查询是
select distinct m.patid
,m.sex
,(DATEPART(year,min(c.admitdate)) -m.yrdob)/10 as decades
from members as m
inner join claims as c on c.patid=m.PATID
group by m.PATID, m.sex,m.yrdob
编辑:第二个查询的结果
所以我需要sum
第二个查询中的十年列在第一个查询中相等counts
。我尝试的(并返回零结果)如下。我需要做什么来匹配这些年龄?
运行但不返回结果的查询:
select x.PATID--,x.sex,x.decades,y.counts
from
(
select distinct m.patid
,m.sex
,(DATEPART(year,min(c.admitdate)) -m.yrdob)/10 as decades
from members as m
inner join claims as c on c.patid=m.PATID
group by m.PATID, m.sex,m.yrdob
) as x
inner join
(
select sex, age/10 as decades,COUNT(*) as counts
from
(
select distinct m.patid
,m.sex,DATEPART(year,min(c.admitdate)) -m.yrdob as Age
from members as m
inner join claims as c on c.patid=m.PATID
group by m.PATID, m.sex,m.yrdob
)x group by sex, Age/10
) as y on x.sex=y.sex and x.decades=y.decades
group by y.counts,x.PATID,x.sex,y.sex
having SUM(x.decades)=y.counts and x.sex=y.sex