子查询中的子查询

时间:2016-11-11 09:08:19

标签: sql sql-server

我有下表:

+-------------+------------+----------+-----------+-----------+
|  Patient No | Event Date | Exam Key | Event Key | Exam Code |
+-------------+------------+----------+-----------+-----------+
|           1 | 27/12/2015 |     4380 |      4792 | XHIPL     |
|           1 | 27/12/2015 |     4379 |      4792 | XPELV     |
|           2 | 11/02/2016 |     7006 |      2390 | XPELV     |
|           3 | 17/11/2015 |     5785 |      3948 | XHIPR     |
|           3 | 17/11/2015 |     5784 |      3948 | XPELV     |
|           4 | 13/03/2016 |     2633 |      7792 | XPELV     |
|           4 | 13/03/2016 |     2634 |      7792 | XHIPR     |
|           5 | 06/05/2016 |     6188 |      9169 | XHIPL     |
|           5 | 06/05/2016 |     6187 |      9169 | XPELV     |
|           6 | 05/09/2016 |     3396 |      3809 | XHIPR     |
|           6 | 05/09/2016 |     3397 |      3809 | XPELV     |
|           7 | 22/02/2016 |     8337 |      3706 | XPELV     |
|           7 | 22/02/2016 |     8336 |      3706 | XHIPL     |
|           8 | 27/11/2015 |     9376 |      7063 | XPELV     |
+-------------+------------+----------+-----------+-----------+

我想展示那些患有XPELV病毒的患者。和' XHIPL'或者' XPELV'和' XHIPR'

3 个答案:

答案 0 :(得分:1)

这可以为您提供所需的结果:

SELECT T.*
FROM TABLE T
    INNER JOIN TABLE TT ON T.[Patient No] = TT.[Patient No]
WHERE TT.[Exam Code] = 'XPELV'
    AND EXISTS(SELECT 1 
               FROM TABLE T2 
               WHERE TT.[Patient No]=T2.[Patient No] 
                   AND (T2.[Exam Code] = 'XHIPL'
                       OR
                       T2.[Exam Code] = 'XHIPR')
               )

答案 1 :(得分:1)

经过几次测试后,这似乎是最有效的方式:

select 
    t.PatientNo,
    t.EventDate,
    t.ExamKey,
    t.EventKey,
    t.ExamCode
from #Temp as [t]
where t.ExamCode in ('XHIPL', 'XHIPR')
    and t.PatientNo in (select t2.PatientNo from #Temp as [t2] where t2.ExamCode = 'XPELV')

我为你尝试了几个CTE,上面的答案使用了EXISTS。在比较计划时,这种方法很有效(我的意思是吝啬!)。

答案 2 :(得分:1)

此查询返回所需的输出:

SELECT  *
FROM    Patient
WHERE   [Patient No] IN (
        SELECT  DISTINCT
                p.[Patient No]
        FROM    Patient p
                JOIN ( SELECT   *
                       FROM     Patient
                       WHERE    [Exam Code] = 'XPELV'
                     ) pp ON p.[Patient No] = pp.[Patient No]
        WHERE   p.[Exam Code] IN ( 'XHIPL', 'XHIPR' ) ) ;

结果:

enter image description here