仅显示除NULL之外的每个组的第一行

时间:2014-01-14 07:32:45

标签: sql sql-server sql-server-2008

我有一张病人表。患者可以单身或结婚。我想按字母顺序列出所有患者,但我想只为已婚夫妇展示女性患者(忽略丈夫)。
如果多个患者有相同的CaseNo,我认为他们是夫妻 性别:0是女性,1是男性。

PatientID  CaseNo  Gender  Name
1          1       1       Mike
2          NULL    0       Pamela
3          2       0       Mary
4          2       1       John
5          NULL    1       Dave

预期输出为:

PatientID  CaseNo  Gender  Name
5          NULL    1       Dave
3          2       0       Mary
1          1       1       Mike
2          NULL    0       Pamela

约翰被排除在外,因为他的妻子在名单上。

我尝试one of the answers in this question,但它排除了CaseNo为NULL的记录。

WITH cte 
     AS (SELECT PatientID, 
                CaseNo, 
                Gender, 
                Name, 
                Row_number() 
                  OVER ( 
                    partition BY CaseNo
                    ORDER BY Gender DESC) rn 
         FROM Patients) 
SELECT PatientID, 
       CaseNo, 
       Gender, 
       Name

FROM   cte 
WHERE  rn = 1 
ORDER BY Name

有可能实现这个目标吗?

2 个答案:

答案 0 :(得分:2)

你可以这样试试

SELECT PatientID, CaseNo, Gender, Name
  FROM 
(
  SELECT PatientID, CaseNo, Gender, Name, 
         ROW_NUMBER() OVER (PARTITION BY CaseNo ORDER BY Gender) rnum,
         COUNT(*) OVER (PARTITION BY CaseNo) rcnt
    FROM Patients
) q
 WHERE CaseNo IS NULL 
    OR rcnt = 1
    OR (rcnt > 1 AND rnum = 1)
 ORDER  BY Name

输出:

| PATIENTID | CASENO | GENDER |   NAME |
|-----------|--------|--------|--------|
|         5 | (null) |      1 |   Dave |
|         3 |      2 |      0 |   Mary |
|         1 |      1 |      1 |   Mike |
|         2 | (null) |      0 | Pamela |

这是 SQLFiddle 演示

答案 1 :(得分:1)

查询:

<强> SQLFIDDLEExample

  WITH cte 
     AS (SELECT PatientID, 
                CaseNo, 
                Gender, 
                Name, 
               CASE WHEN CaseNo is null
               THEN 1 
               ELSE  Row_number() 
                  OVER ( 
                    partition BY CaseNo
                    ORDER BY Gender ASC) END  rn 
         FROM Patients) 
SELECT PatientID, 
       CaseNo, 
       Gender, 
       Name

FROM   cte 
WHERE  rn = 1 
ORDER BY Name asc

结果:

| PATIENTID | CASENO | GENDER |   NAME |
|-----------|--------|--------|--------|
|         5 | (null) |      1 |   Dave |
|         3 |      2 |      0 |   Mary |
|         1 |      1 |      1 |   Mike |
|         2 | (null) |      0 | Pamela |