使用JOIN获取DISTINCT记录

时间:2013-03-18 12:02:54

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

我想拍摄不同的病历并在网格中显示

患者表

PatientId, FirstName, LastName, City

预订表

BookingId, PatientId, CategoryId, BookingDate

在查询下方运行会提供重复的患者记录。发生这种情况是因为我为不同日期的同一患者预订了3次。该查询进行连接并带来3个患者记录而不是1个患者记录。

 SELECT  DISTINCT PAT.PatientId  
 ,PAT.FirstName
 ,PAT.LastName      

 ,ROW_NUMBER() OVER (ORDER BY PAT.PatientId DESC) AS RowNumber 
 INTO #itemSearch  
 FROM  dbo.Patient AS PAT  

 INNER JOIN dbo.Booking AS B  
 ON PAT.PatientId = B.PatientId WHERE  B.CategoryId = 1

如果我删除这一行,我只得到1.但我需要这个临时表用于其他分页过程。

ROW_NUMBER() OVER (ORDER BY PAT.PatientId DESC) AS RowNumber INTO #itemSearch  

即使有3位预订,我怎样才能获得1位患者?

1 个答案:

答案 0 :(得分:2)

使用GROUP BY子句

 SELECT PAT.PatientId  
        ,PAT.FirstName
        ,PAT.LastName      
        ,ROW_NUMBER() OVER (ORDER BY PAT.PatientId DESC) AS RowNumber 
 INTO #itemSearch  
 FROM  dbo.Patient AS PAT  
   INNER JOIN dbo.Booking AS B  
     ON PAT.PatientId = B.PatientId 
 WHERE  B.CategoryId = 1
 GROUP BY PAT.PatientId, PAT.FirstName, PAT.LastName

或者使用带有DENSE_RANK()排名函数的DISTINCT

 SELECT DISTINCT PAT.PatientId  
        ,PAT.FirstName
        ,PAT.LastName      
        ,DENSE_RANK() OVER (ORDER BY PAT.PatientId DESC) AS RowNumber 
 INTO #itemSearch  
 FROM  dbo.Patient AS PAT  
   INNER JOIN dbo.Booking AS B  
     ON PAT.PatientId = B.PatientId 
 WHERE  B.CategoryId = 1