表达:
count(BIDdetails.Origin)
只计算每个组中的BIDdetails.Origin
非空值的数量。因为您实际上是按字段进行分组,所以这将是每个组中的行数。
通过在唯一标识符上使用count(distinct)
,您可以在大多数数据库中获得您想要的结果。唉,MS Access不支持count(distinct)
,所以这样的查询在Access中编写起来要困难得多。您可以通过执行得到公正的count
领域:
SELECT BIDdetails.Origin, BIDdetails.Destination, count(*) as NoOfShpt
FROM BIDdetails
where BIDdetails.OrgCountry <> 'AE' and BIDdetails.DestCountry='AE' and
BIDdetails.ClosingDate>=#" & dtpBIDfrom.Value & "# and BIDdetails.ClosingDate<=#" & dtpBIDto.Value & "#
GROUP BY BIDdetails.Origin, BIDdetails.Destination;
然后结合无论是在您的应用程序或通过加入该查询返回到原来的结果。
编辑:
这是原始查询:
SELECT d.Origin, d.Destination,
Round(Sum(Dims.ChargeableWeight)) as CWeight, count(d.Origin) as NoOfShpt
FROM BIDdetails as d LEFT JOIN
DIMS
ON BidDetails.BID=Dims.BID
where d.OrgCountry <> 'AE' and d.DestCountry='AE' and
d.ClosingDate> = #" & d.Value & "# and d.ClosingDate<=#" & dtpBIDto.Value & "#
GROUP BY d.Origin, d.Destination
ORDER BY Round(Sum(Dims.ChargeableWeight)) DESC
还有一个办法,你先通过聚合的细节,然后再。我认为,在这种情况下更容易:
SELECT Origin, Destination, SUM(CWeight) as CWeight, COUNT(*) as NumShip
FROM (SELECT d.id, d.Origin, d.Destination,
Round(Sum(Dims.ChargeableWeight)) as CWeight, count(d.Origin) as NoOfShpt
FROM BIDdetails as d LEFT JOIN
DIMS
ON BidDetails.BID = Dims.BID
where d.OrgCountry <> 'AE' and d.DestCountry='AE' and
d.ClosingDate> = #" & d.Value & "# and d.ClosingDate<=#" & dtpBIDto.Value & "#
GROUP BY d.id, d.Origin, d.Destination
) as d
GROUP BY Origin, Destination
ORDER BY Round(Sum(CWeight)) DESC;
d.id
是指任何独有的ID是你想算什么。
因为大概'Dims'对于'BIDetails'中的每一行都有多行,尽管您没有提供足够的细节供我们确定。如果是这样的话,你需要在子查询中进行预先聚合。注意:串联是引入SQL注入的好方法,你应该使用参数化查询。 – 2014-11-15 05:43:42