我有一个用户填写的表格,当患者转移到另一个地方时。
表单的相关部分如下所示:
我想计算没有Date of Return
的患者数量。
相关表格 -
form_names - 表单列表
select id, name from form_names where id = 47
id name
----- ----------------------
47 Transfer of Health Information
form_items - 列出每个表单(form_name
)的问题。
select id, form_name, text from form_items where form_name = 47
id form_name text
----------- ----------- ------------------------------------
1147 47 Date of Transfer:
1148 47 Sending Facility:
1155 47 Date of Return:
form_records - 表明特定患者(pid
)填写表单(form_name
)的记录。
select id, pid, date, form_name From form_records where pid = 260 and form_name = 47
id pid date form_name
----------- ----------- ----------------------- -----------
16409 260 2013-04-24 09:33:29.000 47
现在,最后一个相关表是form_answers表。 此表格中仅填写完整的答案。
正如您所看到的,由于Date of Return
值从未在表单中填写过,因此它永远不会出现在此表中:
select id, form_record, form_item, text from form_answers where form_record = 16409
id form_record form_item text
-------------------- ----------- ----------- -----------------------------------------
354535 16409 1147 04-24-2013
354536 16409 1148 Lawrence Jail
354537 16409 1149 Lawrence County Hospital
354538 16409 1151 NKMA
我尝试过类似的东西,但它不起作用:
select
count(*)
from
form_names fn
inner join form_items fi on fn.id = fi.form_name
inner join form_records fr on fn.id = fr.form_name
left outer join form_answers fa on fr.id = fa.form_record and fi.id = fa.form_item
where
fn.name like '%Transfer of Health Information%'
and dateadd(dd, 0, datediff(dd, 0, fr.date)) = dateadd(dd, 0, datediff(dd, 0, getdate()))
and fi.text like '%receiving facility%'
and fa.id is NULL
如何找到没有返回日期的患者数量
答案 0 :(得分:0)
我认为答案的加入是不正确的。您需要同时加入项目和fr.id:
select count(*) -- should this be "count(distinct pid)"?
from form_names fn inner join
form_items fi
on fn.id = fi.form_name inner join
form_records fr
on fn.id = fr.form_name left outer join
form_answers fa
on fn.id = fa.form_item and fa.form_record = fr.id
where fn.name like '%Transfer of Health Information%'
fn.text like '%Date of Return%' and
dateadd(dd, 0, datediff(dd, 0, fr.date)) = dateadd(dd, 0, datediff(dd, 0, getdate())) and
fi.text like '%receiving facility%' and
fa.id is NULL;
您查询失败,因为某些其他表单符合条件。
顺便说一句,我发现让外键与主键的名称相匹配要容易得多。除此之外,外键应该是表格的名称,后跟_id
或Id
。