我有一个查询可以获取像这样的客户的产品数量
SELECT top(4)
count([Product]) as p
, Product
FROM CustomerProducts
WHERE CustomerID = '123'
GROUP BY Product
ORDER BY p desc
这行得通,会给我例如,也会给我例如
154 Bike
100 Truck
90 Tracktor
80 Buggy
现在,我需要让所有前4名拥有自行车的客户获得成功。我尝试使用子查询来成功完成此操作。
SELECT CustomerID
WHERE Product
EXISTS IN {customers top 4 products}
这是我正在尝试实现的查询
您可以使用进行此操作APPLY
,但是,如果它是一个大表,请不要在生产环境中运行类似的操作(因为这可能是非常繁重的查询)。
另外查询未经测试。但是应该可以。
SELECT cp.CustomerID
FROM CustomerProducts cp
CROSS APPLY (
SELECT TOP 4 xp.Product, count(*)
FROM CustomerProducts xp
WHERE xp.CustomerId = cp.CustomerId
GROUP BY xp.Product
ORDER BY COUNT(*) DESC
) xrp
WHERE xrp.Product = 'Bike'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句