2014-11-14 102 views
-1

此SQL正在返回表Dim的記錄計數,而不是返回表BIDdetails的記錄計數。我該如何解決?SQL返回錯誤表的計數

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") 
+0

因爲大概'Dims'對於'BIDetails'中的每一行都有多行,儘管您沒有提供足夠的細節供我們確定。如果是這樣的話,你需要在子查詢中進行預先聚合。注意:串聯是引入SQL注入的好方法,你應該使用參數化查詢。 – 2014-11-15 05:43:42

回答

1

表達:

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是你想算什麼。

+0

嗨戈登,謝謝你的迅速答覆。你能否給我完整的聲明,包括** LEFT JOIN?**,因爲上述不適合我。 – 2014-11-15 06:30:39