我有一个查询和结果:
SELECT DISTINCT dbo.raTMS_TruckLoadingArm.ProductFK,
dbo.raTMS_TruckLoadingBay.BayName
FROM
dbo.raTMS_TruckLoadingArm
INNER JOIN dbo.raTMS_TruckLoadingBay ON dbo.raTMS_TruckLoadingArm.TruckLoadingBayFK = dbo.raTMS_TruckLoadingBay.PriKey
WHERE
dbo.raTMS_TruckLoadingArm.ProductFK IN (8, 9, 11, 10, 7)
ORDER BY BayName
结果:
我想从上面的查询中选择并按'BayName'分组,其中'Bayname'有行数 = 4,所以结果应该只是“Bay1”
提前谢谢!
答案 0 :(得分:2)
如果我理解正确,您可以使用带有HAVING
子句的简单聚合来执行此操作:
SELECT b.BayName
FROM dbo.raTMS_TruckLoadingArm a INNER JOIN
dbo.raTMS_TruckLoadingBay b
ON a.TruckLoadingBayFK = b.PriKey
WHERE a.ProductFK IN (8, 9, 11, 10, 7)
GROUP BY b.BayName
HAVING COUNT(DISTINCT a.ProductFK) = 4;
请注意,使用表别名可以使查询更容易编写和读取。