在SQL Server中比较多行

时间:2015-02-13 12:52:55

标签: sql sql-server

我有一个SQL Server数据库,其中包含以下结构中的以下(虚构)数据:

ID | PatientID | Exam | (NON DB COLUMN FOR REFERENCE)
------------------------------------
1  | 12345     | CT   | OK
2  | 11234     | CT   | OK(Same PID but Different Exam)
3  | 11234     | MRI  | OK(Same PID but Different Exam)
4  | 11123     | CT   | BAD(Same PID, Same Exam)
5  | 11123     | CT   | BAD(Same PID, Same Exam)
6  | 11112     | CT   | BAD(Conflicts With ID 8)
7  | 11112     | MRI  | OK(SAME PID but different Exam)
8  | 11112     | CT   | BAD(Conflicts With ID 6)
9  | 11123     | CT   | BAD(Same PID, Same Exam)
10 | 11123     | CT   | BAD(Same PID, Same Exam)

我正在尝试编写一个查询,并根据我上面的例子,查看一切并不坏的内容。

总体而言,患者(由PatientId标识)可以有多行,但可能没有2行或更多行具有相同的检查!

我尝试过对这里的考试进行各种修改,但仍然没有运气。

感谢。

5 个答案:

答案 0 :(得分:3)

您似乎想要识别重复项,将其排名为goodbad。这是一个使用窗口函数的方法:

select t.id, t.patientid, t.exam,
       (case when cnt > 1 then 'BAD' else 'OK' end)
from (select t.*, count(*) over (partition by patientid, exam) as cnt
      from table t
     ) t;

答案 1 :(得分:0)

使用Count() over()

select *,case when COUNT(*) over(partition by PatientID, Exam) > 1 then 'bad' else 'ok' 
from yourtable 

答案 2 :(得分:0)

您也可以使用:

 ;WITH  CTE_Patients
      (ID, PatientID, Exam, RowNumber)
AS
(
      SELECT      ID, PatientID, Exam
                  ROW_NUMBER() OVER (PARTITION BY PatientID, Exam ORDER BY ID)
      FROM        YourTableName
)
SELECT      TableB.ID, TableB.PatientID, TableB.Exam, [DuplicateOf] = TableA.ID
FROM        CTE_Patients TableB
INNER JOIN CTE_Patients TableA
            ON    TableB.PatientID = TableA.PatientID
            AND   TableB.Exam = TableA.Exam
WHERE       TableB.RowNumber > 1 -- Duplicate rows
AND         TableA.RowNumber = 1 -- Unique rows

我在这里有一个示例:SQL Server – Identifying unique and duplicate rows in a table,您可以识别唯一的行以及重复的行

答案 3 :(得分:0)

如果您不想使用CTECount Over,您还可以group来源表,并从那里选择...(但我会感到惊讶如果@Gordon与原始答案相差太远:))

SELECT  a.PatientID, a.Exam, CASE WHEN a.cnt > 1 THEN 'BAD' ELSE 'OK' END
FROM    ( SELECT    PatientID
                   ,Exam
                   ,COUNT(*) AS cnt
          FROM      tableName
          GROUP BY  Exam
                   ,PatientID
        ) a

答案 4 :(得分:0)

选择那些从未进行过两次或多次相同类型考试的患者。

select * from patients t1
where not exists (select 1 from patients t2
                  where t1.PatientID = t2.PatientID
                  group by exam
                  having count(*) > 1)

或者,如果您想要所有行,例如:

select ID,
       PatientID,
       Exam,
       case when exists (select 1 from patients t2
                         where t1.PatientID = t2.PatientID
                         group by exam
                         having count(*) > 1) then 'BAD' else 'OK' end
from patients