匹配具有特定ID的记录

时间:2018-10-17 13:37:00

标签: sql sql-server tsql

假设我有此查询来匹配具有特定订单1982138923的员工,是否还有另一种方法不使用havinggroup by子句?

我想对具有两个或多个特定订单ID的员工进行排序。

SELECT [EmployeeId], COUNT([OrderId]) 
FROM [dbo].[EmployeeOrderRelation]
WHERE [OrderId] IN (1982, 138923)
GROUP BY [EmployeeId]
HAVING count([OrderId]) > 1;

3 个答案:

答案 0 :(得分:1)

您可以使用EXISTS

SELECT er.*
FROM [dbo].[EmployeeOrderRelation] er
WHERE [OrderId] IN (1982, 138923) AND
      EXISTS (SELECT 1 
              FROM [dbo].[EmployeeOrderRelation] er1 
              WHERE er1.[EmployeeId] = er.[EmployeeId] AND er1.[OrderId] <> er.[OrderId]
             );

我不知道为什么您需要不同版本的查询而不是聚合查询,如果对性能有问题,那么如果您在(EmployeeId,{{1 }})。

答案 1 :(得分:0)

您可以使用相关子查询

SELECT a.* 
 FROM [dbo].[EmployeeOrderRelation] a
 WHERE [OrderId] IN (1982, 138923) and exists (select 1 from [dbo].[EmployeeOrderRelation] b where a.[EmployeeId]=b.[EmployeeId] and b.[OrderId] IN (1982, 138923) having count(orderid)>=2)

答案 2 :(得分:0)

使用INTERSECT返回具有两个值的EmployeeId:

SELECT [EmployeeId] FROM [dbo].[EmployeeOrderRelation] WHERE [OrderId] = 1982
INTERSECT
SELECT [EmployeeId] FROM [dbo].[EmployeeOrderRelation] WHERE [OrderId] = 138923

或进行自我加入:

select t1.[EmployeeId]
from [dbo].[EmployeeOrderRelation] t1
join [dbo].[EmployeeOrderRelation] t2
    on t1.[EmployeeId] = t2.[EmployeeId]
WHERE t1.[OrderId] = 1982
  AND t2.[OrderId] = 138923