选择id(在本例中为dupersid),其中第二列(在本例中为icd9codx)的值仅在(296311)和250中。

| dupersid  | icd9codx
---------------------
46166101    -9
46166101    250
46166101    272
46166101    272
46166101    311
46166101    401
46166101    460
46166101    701
46166101    715
46166101    719
46166101    780
46166102    250
46166102    311
46166103    250
46166103    296

预期结果
----------------------
dupersid    icd9codx
---------------------
46166102    250
46166102    311
46166103    250
46166103    296

我试过了
SELECT dupersid, icd9codx FROM public.sample_test
WHERE icd9codx = 250 AND dupersid IN (select distinct dupersid from public.sample_test where icd9codx IN (296, 311));

但它也提供了像46166101这样的记录

最佳答案

你可以通过将2的幂相加的技巧来实现这一点:

SELECT *
FROM public.sample_test
WHERE dupersid IN(SELECT dupersid FROM public.sample_test
                  GROUP BY dupersid
                  HAVING SUM(CASE icd9codx WHEN 250 THEN 1
                                           WHEN 296 THEN 2
                                           WHEN 311 THEN 4
                                           ELSE 8 END) IN (3, 5) AND
                         SUM(CASE WHEN icd9codx = 250 THEN 1
                                  ELSE 0 END) = 1)

关于mysql - 选择id(在本例中为dupersid),其中第二列(在本例中为icd9codx)中的值位于(296,311)和250中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33848572/

10-09 07:43