如何避免连接查询中的多行?

时间:2017-03-16 12:34:13

标签: sql sql-server

下面是我的SQL查询。如果fbkWeightMaster具有同一患者的多个记录,则会在结果中返回多行。我想避免它。我尝试使用Distinct,但没有用。

我确认在以下查询的fbkWeightMaster表中有多个条目时会出现此问题。

Select Distinct
        a.patientid
      , a.firstname
      , a.lastname
      , a.mobile
      , a.dob
      , b.InitialWeight
      , b.LatestWeight
      , a.height
      , c.PlanName
      , a.warning
      , a.indicator
      , a.city
      , a.email
      , a.state
      , a.comments
      , a.introduction
      , a.gender
      , a.address
      , a.landline
      , a.FoodPreference
From    
    fbkPatientMaster a
Join
    fbkPlanMaster c On a.PlanID = c.PlanID
Join    
    fbkWeightMaster b On a.PatientID = b.PatientID
Join    
    fbkChartMaster d On d.PatientID = a.PatientID
Where   
    IsActive = 1
    And a.PatientID Not In (Select Distinct PatientID
                            From fbkChartMaster
                            Where Cast(ChartDate As Date) = DateAdd(Day, 1, Cast(GetDate() As Date)))
    And a.PatientID Not In (Select Distinct PatientID
                            From fbkChartHold
                            Where Cast(ChartHoldTo As Date) > Cast(GetDate() As Date));

1 个答案:

答案 0 :(得分:4)

您可以根据某个订单(例如select top 1列)将您的加入更改为cross apply()fbkWeightMaster date。这将从fbkWeightMastera.patientid只返回一行。

cross apply()inner join的工作方式类似,如果您想要left join使用outer apply()而获得的功能。

Select 
        a.patientid
      , a.firstname
      , a.lastname
      , a.mobile
      , a.dob
      , b.InitialWeight
      , b.LatestWeight
      , a.height
      , c.PlanName
      , a.warning
      , a.indicator
      , a.city
      , a.email
      , a.state
      , a.comments
      , a.introduction
      , a.gender
      , a.address
      , a.landline
      , a.FoodPreference
From    
    fbkPatientMaster a
Join
    fbkPlanMaster c On a.PlanID = c.PlanID
Join    
    fbkChartMaster d On d.PatientID = a.PatientID
cross apply (
  select top 1 *
  from fbkWeightMaster b 
  where a.PatientID = b.PatientID
  order by b.date desc
) b

Where   
    IsActive = 1
    And a.PatientID Not In (Select Distinct PatientID
                            From fbkChartMaster
                            Where Cast(ChartDate As Date) = DateAdd(Day, 1, Cast(GetDate() As Date)))
    And a.PatientID Not In (Select Distinct PatientID
                            From fbkChartHold
                            Where Cast(ChartHoldTo As Date) > Cast(GetDate() As Date));