0

我有一个带有 2 个 ID 列的 SQL Server 表:Employee_ID & Type_ID

我的表包含 4 行:

Row 1 (Employee ID: 904, Type_ID: 3)
Row 2 (Employee ID: 904, Type_ID: 7)
Row 3 (Employee ID: 905, Type_ID: 7)
Row 4 (Employee ID: 905, Type_ID: 7)

我想返回所有员工可用的所有类型 ID。所以只是ID 7

所以我想要 ID 为 7 的 1 行返回,因为它适用于两个员工(904 和 905)

如果我运行以下 SQL:

SELECT 
    Type_ID, Count(Type_ID) as MyCount 
FROM 
    EmployeeType
WHERE 
    Employee_ID  IN (904, 905)  
GROUP BY 
    Type_ID

这让我返回 2 行

Row 1 (Type_ID: 3, MyCount: 1)
Row 2 (Type_ID: 7, MyCount: 3)

但我只有最高计数的记录(Type_ID 7)。我尝试添加:

HAVING MAX(Count(CostCentre_ID))

但这显然是非法代码。

如何在我的 SQL 中执行此操作?

4

3 回答 3

2

我假设您想找到TypeId分配给 all的EmployeeId

Declare @t table
(
EmployeeId int,
TypeId int
)
Insert Into @t
Select 904, 3
Union 
Select 904, 5
Union 
Select 904, 7
Union 
Select 905, 5
Union 
Select 905, 7
Union 
Select 908, 3
Union 
Select 908, 7


Select Distinct a.TypeId
From @t a
Join 
(
    Select TypeId,
            COUNT(*) Over(Partition by TypeId)as [Occurs]
    From @t
)b on a.TypeId = b.TypeId

Where b.Occurs = (Select COUNT(Distinct(EmployeeId))
                From @t
                )

这将返回7,因为它是唯一TypeId分配给所有员工的。

于 2013-04-09T10:26:38.870 回答
2

受到 Barry 的回答的启发,即使有这样的“重复”行,也能得到正确的结果:

declare @t table (
  employeeid int, typeid int, notes int
)
insert into @t
  select 904, 3, 0 union
  select 904, 5, 0 union
  select 904, 5, 1 union
  select 904, 7, 0 union
  select 905, 7, 0 union
  select 905, 7, 1 union
  select 908, 3, 0 union
  select 908, 5, 0 union
  select 908, 7, 0 union
  select 908, 9, 0 union
  select 908, 3, 0

获取所有typeids 存在的所有employeeids:

select typeid
from @t
group by typeid
having count(distinct employeeid) = (
  select count(distinct employeeid)
  from @t)
于 2013-04-09T12:05:15.917 回答
0

你能试试这个:

SELECT Type_ID, Occurance FROM 
(
SELECT Type_ID, Count(Employee_ID) OVER (PARTITION BY Employee_ID) AS Occurance
FROM EmployeeType
) T
WHERE T.Occurance > 2
于 2013-04-09T10:28:34.827 回答