仅获取第一个结果外连接SQL Server

时间:2016-10-28 12:45:40

标签: sql-server

我有两个表,一个有客户列表,另一个有合同列表。每个客户可以有多个合同。我想获得所有客户的号码,姓名,以及他们是否有合同。这是我的要求:

SELECT c.[no_], 
       c.[name], 
       s.[contract no_] 
FROM   [contact] AS c 
       LEFT OUTER JOIN [service contract header] AS s 
                    ON c.[no_] LIKE s.[contact no_] 
                       AND s.[serv_ contract acc_ gr_ code] LIKE 'SAV' 
ORDER  BY s.[contract no_] 

我得到的结果是所有客户及其合同的清单,如果他们有合同,但如果客户有2份合同,则结果中会出现两次。一旦合同1和合同2.我希望每个客户只有一次出现。知道他是否有合同1或2并不重要,我只想知道他是否有合同。现在还有什么问题:/并且无法弄清楚要在网上搜索什么来找到答案

2 个答案:

答案 0 :(得分:2)

您可以使用GROUP BY返回汇总,COUNT例如可以为您提供合同数量。

SELECT c.[No_], c.[Name], COUNT(s.[Contact No_]) AS Contracts
FROM [Contact] AS c 
LEFT JOIN [Service Contract Header] AS s ON c.[No_] LIKE s.[Contact No_] AND s.[Serv_ Contract Acc_ Gr_ Code] LIKE 'SAV' 
GROUP BY c.[No_], c.[Name]

您还可以在GROUP BY上放置一个过滤器,它被称为HAVING。这将使所有客户返回至少一份合同。

SELECT c.[No_], c.[Name]
FROM [Contact] AS c 
LEFT JOIN [Service Contract Header] AS s ON c.[No_] LIKE s.[Contact No_] AND s.[Serv_ Contract Acc_ Gr_ Code] LIKE 'SAV' 
GROUP BY c.[No_], c.[Name]
HAVING COUNT(s.[Contact No_]) >= 1

答案 1 :(得分:0)

另一种方式是APPLY子句:

SELECT c.[No_], c.[Name], a.cnt as ContactsCount
    FROM [Contact] AS c 
    OUTER APPLY (SELECT count(*) cnt FROM [Service Contract Header] s WHERE c.[No_] = s.[Contact No_] AND s.[Serv_ Contract Acc_ Gr_ Code] = 'SAV') a
    ORDER BY c.[No_]