3

我有一个名为“Patients”的表,看起来像这样

> PatientName      DateOftest    Eye     L1    L2    L3    L4     L5
>     Mike         17-02-2009     L      23    25    40    32     30
>     Mike         17-02-2009     R      25    30    34    35     24
>     Ryan         18-03-2012     R      12    18    27    39     40
>     Bill         08-03-2006     L      20    24    30    24     25
>     Bill         08-03-2006     R      18    25    27    30     24   
>     Chan         03-08-2009     L      18    21    28    35     12

不,我必须从患者只有一个(左眼记录或右眼记录测试)的患者中选择 *.. 结果将是

Ryan         18-03-2012     R      12    18    27    39     40
Chan         03-08-2009     L      18    21    28    35     12
4

4 回答 4

3

你可以这样做:

SELECT *
FROM Patients
WHERE PatientName IN(SELECT PatientName 
                     FROM Patients
                     GROUP BY PatientName 
                     HAVING COUNT(*) = 1);

SQL 小提琴演示

这会给你:

| PATIENTNAME | DATEOFTEST | EYE | L1 | L2 | L3 | L4 | L5 |
-----------------------------------------------------------
|        Ryan | 18-03-2012 |   R | 12 | 18 | 27 | 39 | 40 |
|        Chan | 03-08-2009 |   L | 18 | 21 | 28 | 35 | 12 |
于 2013-02-18T07:42:51.737 回答
1

EXISTS运算符的另一种选择

SELECT *
FROM Patients p1
WHERE EXISTS (
              SELECT 1
              FROM Patients p2
              WHERE p1.PatientName = p2.PatientName
              HAVING COUNT(*) = 1
              )

SQLFiddle上的演示@Mahmoud Gamal 感谢 DDL Schema;)

于 2013-02-18T08:09:01.220 回答
0
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  PatientName
            FROM    tablename
            GROUP   BY PatientName
            HAVING  COUNT(Eye) = 1
        ) b ON a.PatientName = b.PatientName

为了获得更快的性能,请添加一个INDEXon 列PatientName

COUNT(Eye)eye对于有相同记录但不同的患者会做得最好DateOftest

于 2013-02-18T07:44:15.153 回答
0

你可以试试这个

SELECT PatientName, 
       DateOftest, 
       MIN(Eye) AS Eye, 
       MIN(L1) AS L1, MIN(L2) AS L2, MIN(L3) AS L3, MIN(L4) AS L4, MIN(L5) AS L5
FROM patients
GROUP BY PatientName, DateOftest
HAVING COUNT(Eye) = 1

结果

| PATIENTNAME | DATEOFTEST | EYE | L1 | L2 | L3 | L4 | L5 |
-----------------------------------------------------------
|        Chan | 03-08-2009 |   L | 18 | 21 | 28 | 35 | 12 |
|        Ryan | 18-03-2012 |   R | 12 | 18 | 27 | 39 | 40 |

sqlfiddle

于 2013-02-18T07:46:25.093 回答