我有一个名为“患者”的表,看起来像这样
> 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
答案 0 :(得分:3)
你可以这样做:
SELECT *
FROM Patients
WHERE PatientName IN(SELECT PatientName
FROM Patients
GROUP BY PatientName
HAVING COUNT(*) = 1);
这会给你:
| 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 |
答案 1 :(得分: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架构;)
答案 2 :(得分: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
要获得更快的效果,请在列INDEX
上添加PatientName
。
COUNT(Eye)
最适用于记录eye
但DateOftest
不同的患者。
答案 3 :(得分: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 |