SQL QUERY - 具有共同值的人

时间:2017-11-29 17:22:03

标签: sql

假设我有一家医院数据库。 所以...我有一个包含2列的表:patients_ID,treatment_ID和记录让我们说我们有另一个第三主键列,无论究竟是什么。 现在,我想从表中提取所有至少(或更多)ID为'1'的患者所有治疗的患者_ID。

例如:

patients_ID           treatment_ID

    1                     111
    1                     222
    1                     333
    2                     111
    2                     333
    5                     111
    5                     222
    5                     333
    5                     444

如您所见,从上表中我希望我的查询返回表:

patients_ID
     5

因为只有他得到了与患者id = 1相同的治疗,并且我不在乎他除此之外还得到治疗444。

patient_id = 2不属于因为他缺少治疗“222”。

3 个答案:

答案 0 :(得分:0)

为患者1进行所有治疗,将其与除1以外的所有其他患者交叉加入并离开原点并检查相同的治疗计数。

select p.patient_id
from (select treatment_id from tbl where patient_id=1) t
cross join (select distinct patient_id from tbl where patient_id<>1) p
left join tbl on tbl.patient_id=p.patient_id and t.treatment_id=tbl.treatment_id
group by p.patient_id
having count(t.treatment_id) = count(tbl.treatment_id)  

答案 1 :(得分:0)

SELECT
   patients.id
FROM
(
    SELECT treatment_id FROM yourTable WHERE patients_id = 1
)
    filter
CROSS JOIN
    patients   -- A table with all patients
LEFT JOIN
    yourTable
        ON  yourTable.treatment_id = filter.treatment_id
        AND yourTable.patients_id  = patients.id
WHERE
    patients.id <> 1
GROUP BY
    patients.id
HAVING
    COUNT(filter.treatment_id) = COUNT(yourTable.treatment_id)

(如果您没有患者表,那么您真的应该有一个并且应该创建一个。但您可以使用(SELECT patients_id FROM yourTable GROUP BY patients_id)作为最后的手段。)

或者....

SELECT
   yourTable.patients_id
FROM
(
    SELECT treatment_id FROM yourTable WHERE patients_id = 1
)
    filter
INNER JOIN
    yourTable
        ON  yourTable.treatment_id = filter.treatment_id
WHERE
    yourTable.patients_id <> 1
GROUP BY
   yourTable.patients_id
HAVING
    COUNT(yourTable.treatment_id) = (SELECT COUNT(*) FROM yourTable WHERE patients_id = 1)

答案 2 :(得分:0)

使用此脚本,您不仅可以测试至少一次患有1例治疗患者的患者,还可以测试任何其他患者。例如,通过设置@patient_id = 2,您应该获得1和5,依此类推。我也尝试过玩弄记录并且工作正常。

--MSSQL variable declaration
declare @patient_id int;
--MySQL variable declaration and value assignment
--MSSQL value assignment
set @patient_id = 1;

select patients_id as cnt from patients as t 
inner join
    (select distinct treatment_id from patients where patients_id = 
@patient_id) as tr on tr.treatment_id = t.treatment_id 
group by patients_id 
having count(distinct t.treatment_id)  = (select count(distinct 
treatment_id) from patients where patients_id = @patient_id) 
and patients_id <> @patient_id