我的SQL Server数据库中有一个表,用于存储UserID
,医疗状况的名称以及该病情的诊断日期。
UserID ConditionName DiagnosisDate
9038 Hypertension 1971-07-14
9039 Diabetes 1964-05-13
每个用户可以具有多种医疗条件(即,具有用户ID 9038的用户可能患有头痛,糖尿病和高血压)。
我想写一个查找用户合并症的查询。
例如,我想知道有多少高血压患者也患有糖尿病。
答案 0 :(得分:3)
这显示了具有多种医疗条件的所有用户:
SELECT UserID, COUNT(DISTINCT ConditionName) AS medical_conditions
FROM <TABLE>
GROUP BY UserID
HAVING medical_conditions >= 2;
如果您想搜索特定的医疗条件,可以使用IN
和子查询:
SELECT UserID
FROM <TABLE>
WHERE ConditionName = 'Diabetes'
AND UserID IN (SELECT UserID FROM <TABLE> WHERE ConditionName = 'Hypertension');
答案 1 :(得分:2)
您可以使用子选择来执行此操作:
SELECT COUNT(*) FROM YourTable
WHERE ConditionName = 'Hypertension'
AND UserID IN
(
SELECT UserID FROM YourTable
WHERE ConditionName = 'Diabetes'
);
这将为您提供所有高血压记录的计数。如果UserID可以多次具有相同的条件,则必须将COUNT(*)
替换为COUNT(DISTINCT UserID)
。
答案 2 :(得分:1)
有很多解决方案。使用IN
SELECT count(*)
FROM tab
WHERE userid IN (SELECT t2.userid FROM tab t2 WHERE t2.ConditionName = 'Hypertension') and
userid IN (SELECT t2.userid FROM tab t2 WHERE t2.ConditionName = 'Diabetes')
使用EXISTS
SELECT count(*)
FROM tab t1
WHERE EXISTS(SELECT 1 FROM tab t2 WHERE t2.ConditionName = 'Hypertension' AND t2.userid = t1.userid) and
EXISTS(SELECT 1 FROM tab t2 WHERE t2.ConditionName = 'Diabetes' AND t2.userid = t1.userid)
使用INTERSECT
SELECT count(*)
FROM
(
SELECT userid FROM tab WHERE ConditionName = 'Hypertension'
INTERSECT
SELECT userid FROM tab WHERE ConditionName = 'Diabetes'
) x
使用GROUP BY
SELECT userid
FROM tab
WHERE ConditionName = 'Diabetes' or ConditionName = 'Hypertension'
GROUP BY userid
HAVING count(distinct ConditionName) = 2;
答案 3 :(得分:0)
select count(1)
from yourTable t
where t.ConditionName = 'hypertension'
and exists (
select 1
from yourTable ref
where ref.UserId = t.UserId
and ref.ConditionName = 'diabetes'
)