将现有的sql更改为仅在首次匹配时左连接

时间:2019-06-17 20:19:36

标签: sql sql-server

出于历史目的添加一些原始信息,因为我认为简化会有所帮助,但没有帮助。我们有此存储过程,在这一部分中,它是从表A中选择记录(calldetail_reporting_agents),并对表B进行左连接(Intx_Participant)。显然,表B中有重复的行被我们不想删除。有什么简单的方法可以将其更改为仅选择表B上的第一个匹配项?还是我需要重写整个内容?

SELECT 'Agent Calls' AS CallType,
          CallDate,
          CallTime,
          RemoteNumber,
          DialedNumber,
          RemoteName,
          LocalUserId,
          CallDurationSeconds,
          Answered,
          AnswerSpeed,
          InvalidCall,
          Intx_Participant.Duration
  FROM calldetail_reporting_agents
  LEFT JOIN Intx_Participant ON calldetail_reporting_agents.CallID = Intx_Participant.CallIDKey
  WHERE  DialedNumber IN (  SELECT DialedNumber
                            FROM   #DialedNumbers )
     AND ConnectedDate BETWEEN @LocStartDate AND @LocEndDate
     AND (@LocQueue IS NULL OR AssignedWorkGroup = @LocQueue)

更简单的版本:如何在下面进行更改以仅从表B中选择第一个匹配的行:

SELECT columnA, columnB FROM TableA LEFT JOIN TableB ON someColumn

我根据第一个答案将其更改为该值,现在所有数据看起来都完全符合预期。谢谢大家的迅速而周到的帮助。

SELECT 'Agent Calls' AS CallType,
          CallDate,
          CallTime,
          RemoteNumber,
          DialedNumber,
          RemoteName,
          LocalUserId,
          CallDurationSeconds,
          Answered,
          AnswerSpeed,
          InvalidCall,
          Intx_Participant.Duration
  FROM calldetail_reporting_agents
  OUTER APPLY (SELECT TOP 1
                      *
                      FROM Intx_Participant ip
                      WHERE calldetail_reporting_agents.CallID = ip.CallIDKey 
                      AND calldetail_reporting_agents.RemoteNumber = ip.ConnValue 
                      AND ip.HowEnded = '9' 
                      AND ip.Recorded = '0' 
                      AND ip.Duration > 0 
                      AND ip.Role = '1') Intx_Participant
  WHERE  DialedNumber IN (  SELECT DialedNumber
                            FROM   #DialedNumbers )
     AND ConnectedDate BETWEEN @LocStartDate AND @LocEndDate
     AND (@LocQueue IS NULL OR AssignedWorkGroup = @LocQueue)

1 个答案:

答案 0 :(得分:2)

您可以尝试OUTER APPLY子查询仅获得一个匹配的行。

...
FROM calldetail_reporting_agents
     OUTER APPLY (SELECT TOP 1
                         *
                         FROM intx_Participant ip
                         WHERE ip.callidkey = calldetail_reporting_agents.callid) intx_participant
WHERE ...

您应该在子查询中添加ORDER BY。否则,不能确定哪一行是第一行。也许这不是问题。