简体   繁体   English

SQL选择多列中存在的多个值

[英]SQL select multiple values present in multiple columns

I have two tables DiagnosisCodes and DiagnosisConditions as shown below. 我有两个表DiagnosisCodes和DiagnosisConditions,如下所示。 I need to find the members(IDs) who have a combination of Hypertension and Diabetes. 我需要找到患有高血压和糖尿病的成员(ID)。 The problem here is the DiagnosisCodes are spread across 10 columns. 这里的问题是DiagnosisCodes分布在10列。 How do I check if the member qualifies for both conditions 如何检查该成员是否符合这两个条件

DiagnosisCodes DiagnosisCodes

+----+-------+-------+-------+-----+--------+
| ID | Diag1 | Diag2 | Diag3 | ... | Diag10 |
+----+-------+-------+-------+-----+--------+
| A  |  2502 |  2593 | NULL  | ... | NULL   |
| B  |  2F93 |  2509 | 2593  | ... | NULL   |
| C  |  C257 |  2509 | C6375 | ... | NULL   |
+----+-------+-------+-------+-----+--------+

DiagnosisConditions DiagnosisConditions

+------+--------------+
| Code |  Condition   |
+------+--------------+
| 2502 | Hypertension |
| 2593 | Diabetes     |
| 2509 | Diabetes     |
| 2F93 | Hypertension |
| 2673 | HeartFailure |
+------+--------------+

Expected Result 预期结果

+---------+
| Members |
+---------+
| A       |
| B       |
+---------+

How do I query to check Mulitple values which are present in Multiple columns. 如何查询以检查多列中存在的多个值。 Do you suggest to use EXISTS ? 你建议使用EXISTS吗?

SELECT DISTINCT id 
FROM   diagnosiscodes 
WHERE  ( diag1, diag2...diag10 ) IN (SELECT code 
                                     FROM   diagnosiscondition 
                                     WHERE  condition IN ( 'Hypertension','Diabetes' ) 
                                     ) 

I would do this using group by and having : 我会使用group byhaving来做到这一点:

select dc.id
from diagnosiscodes dc join
     diagnosiscondistions dcon
     on dcon.code in (dc.diag1, dc.diag2, . . . )
group by id
having sum(case when dcon.condition = 'diabetes' then 1 else 0 end) > 0 and
       sum(case when dcon.condition = 'Hypertension' then 1 else 0 end) > 0;

Then, you should fix your data structure. 然后,您应该修复您的数据结构。 Having separate columns with the same information distinguished by a number is usually a sign of a poor data structure. 具有由数字区分的相同信息的单独列通常是不良数据结构的标志。 You should have a table, called somethhing like PatientDiagnoses with one row per patient and diagnosis. 你应该有一个表,称为somethhing像PatientDiagnoses与每名患者和诊断一行。

Here is one way by unpivoting the data 这是通过取消数据的一种方式

SELECT DISTINCT id
FROM   yourtable
       CROSS apply (VALUES (Diag1),(Diag2),..(Diag10))tc(Diag)
WHERE  Diag IN (SELECT code
                FROM   diagnosiscondition
                WHERE  condition IN ( 'Hypertension', 'Diabetes' ) group by code having count(distinct condition)=2) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM