联接查询仅检索匹配的1行

时间:2018-09-18 09:50:59

标签: sql-server join having-clause

我有以下两个表:

用户

  • 用户ID
  • 名称
  • 类型

UserCompany

  • CompanyID
  • 用户ID

公司

  • CompanyID
  • 名称

我希望所有类型只有5个用户的公司。

为什么该查询不起作用?

SELECT C.Name FROM USER u 
JOIN UserCompany UC on u.UserID = UC.UserID 
JOIN Company C on uc.companyID = c.companyID
WHERE u.Type = 5
GROUP BY u.name
HAVING COUNT(u.name) = 1 

样品数据

用户表:

1 John 1
2 Beth 2 
3 Mike 5
4 John 5

公司表:

1 XYZ 
2 KBC
3 MMM

UserCompany

1 1 
1 3
1 4
2 3
2 1

=>应该返回公司2,因为它只有1个用户,其类型为5

2 个答案:

答案 0 :(得分:1)

好的,所以我重新创建了示例表,以便我们可以在SSMS中使用它们;

IF OBJECT_ID('tempdb..#User') IS NOT NULL DROP TABLE #User
CREATE TABLE #User (UserID int, Name nvarchar(4), Type int)
INSERT INTO #User (UserID, Name, Type)
VALUES
 (1,'John',1)
,(2,'Beth',2)
,(3,'Mike',5)
,(4,'John',5)

IF OBJECT_ID('tempdb..#Company') IS NOT NULL DROP TABLE #Company
CREATE TABLE #Company (CompanyID int, Name nvarchar(3))
INSERT INTO #Company (CompanyID, Name)
VALUES
 (1,'XYZ')
,(2,'KBC')
,(3,'MMM')

我不得不猜测您的列标题,因为它们不在示例数据中。这很有趣,因为我猜测表UserCompany的UserID和CompanyID与标题的顺序相同。当我查看此内容时,表明您根本没有用户3。为此,我将假定它实际上是该顺序的CompanyID和UserID。

IF OBJECT_ID('tempdb..#UserCompany') IS NOT NULL DROP TABLE #UserCompany
CREATE TABLE #UserCompany (CompanyID int, UserID int)
INSERT INTO #UserCompany (CompanyID, UserID)
VALUES
 (1,1)
,(1,3)
,(1,4)
,(2,3)
,(2,1)

假设这是正确的,您将想要执行以下操作;

SELECT
    c.Name AS Company_Name
    ,COUNT(u.UserID) Employees
FROM #Company c
INNER JOIN #UserCompany uc 
    ON c.CompanyID = uc.CompanyID
INNER JOIN #User u 
    ON uc.UserID = u.UserID
    AND u.Type = 5
GROUP BY c.Name
HAVING Count(u.UserID) > 1

哪个会给你输出;

Company_Name    Employees
XYZ             2

答案 1 :(得分:0)

我只更新HAVING子句:

SELECT UC.companyID 
FROM USER u JOIN 
     UserCompany UC 
     ON u.UserID = UC.UserID JOIN 
     Company C 
     ON uc.companyID = c.companyID
GROUP BY UC.companyID
HAVING SUM(CASE WHEN U.TYPE = 5 THEN 1 ELSE 0 END) = 1;