用内连接分组并计数

时间:2011-08-05 10:05:21

标签: sql

我有一张包含订单的表和一张包含材料的表(1:N)。 我想知道在特定生产订单和国家/地区的物料表中有多少订单具有屏幕。

底部的查询为我提供了每个订单的每个订单的屏幕数量,而不是预期的结果5:

6
1 
6
2
2 

SELECT Count(ORD.ORDERNUMMER)
FROM        Orders AS ORD
INNER JOIN Material AS KP ON KP.Ordernummer = ORD.Ordernummer
WHERE (KP.SOORT = 'SCREEN') AND ORD.PRODUCTIEORDER = '201132' AND ORD.LAND = 'Belgie'
Group By ORD.Ordernummer HAVING (COUNT(*) >= 1)

我只想要5回复。

提前致谢,

麦克

2 个答案:

答案 0 :(得分:2)

如果每个不同的订单至少包含一行屏幕材料,则需要对其进行计数。

SELECT Count(DISTINCT ORD.ORDERNUMMER)
FROM        Orders AS ORD
INNER JOIN Material AS KP ON KP.Ordernummer = ORD.Ordernummer
WHERE (KP.SOORT = 'SCREEN') AND ORD.PRODUCTIEORDER = '201132' AND ORD.LAND = 'Belgie'

答案 1 :(得分:1)

如果您需要整个结果,请不要对结果进行分组!

SELECT Count(ORD.ORDERNUMMER) as totalScreens
FROM Orders AS ORD
INNER JOIN Material AS KP ON KP.Ordernummer = ORD.Ordernummer
WHERE (KP.SOORT = 'SCREEN') AND ORD.PRODUCTIEORDER = '201132' AND ORD.LAND = 'Belgie'
HAVING (totalScreens >= 1)