【问题标题】:SQL returning the count from wrong tableSQL 返回错误表的计数
【发布时间】:2014-11-14 21:57:40
【问题描述】:

此 SQL 返回表 Dims 的记录数,而不是返回表 BIDdetails 的记录数。我该如何解决?

BIDReportSearch.CommandText = ("SELECT BIDdetails.Origin, BIDdetails.Destination,
Round(Sum(Dims.ChargeableWeight)) as CWeight, count(BIDdetails.Origin) as NoOfShpt
FROM BIDdetails LEFT JOIN DIMS ON BidDetails.BID=Dims.BID
where BIDdetails.OrgCountry<>'AE' and BIDdetails.DestCountry='AE' and
BIDdetails.ClosingDate>=#" & dtpBIDfrom.Value & "# and BIDdetails.ClosingDate<=#" &
dtpBIDto.Value & "# GROUP BY BIDdetails.Origin, BIDdetails.Destination
ORDER BY Round(Sum(Dims.ChargeableWeight)) DESC")

【问题讨论】:

  • 因为,据推测,DimsBIDetails 中的每一行都有多行,尽管您没有提供足够的细节让我们确定。如果是这种情况,您需要在子查询中进行预聚合。旁注:连接是引入 SQL 注入的好方法,您应该使用参数化查询。

标签: sql ms-access vba left-join ms-access-2010


【解决方案1】:

表达式:

count(BIDdetails.Origin)

只计算每个组中BIDdetails.Origin 的非NULL 值的数量。因为您实际上是按字段分组,所以这将是每个组中的行数。

您可以通过在唯一标识符上使用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。

【讨论】:

  • 嗨,戈登,感谢您的迅速回复。您能否给我完整的声明,包括 LEFT JOIN? 因为上述内容不适合我。
猜你喜欢
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 2017-03-19
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多