2012-07-05 173 views
3

我有這3個表: enter image description hereIIF語句在MS-訪問

,我使用此代碼它們連接在一起(我用Delphi):

ADOQ.SQL.Text := 'select a.IdArt as [Code d''Article], '+ 
        'a.Nom,'+ 
        'Str(a.Prix)+" TND" as Prix, '+ 
        '(select Str(sum(QteEntree))+" "+a.unit from Stock where IdArt = a.IdArt group by IdArt) as [Quantite Entree],' + 
        '(select Str(sum(Qte))+" "+a.unit from Sold where IdArt = a.IdArt group by IdArt) as [Quantite Vendu],'+ 
        'Str((select sum(QteEntree) from Stock where IdArt = a.IdArt group by IdArt) -' + 
        '(select sum(Qte) from Sold where IdArt = a.IdArt group by IdArt))+" "+a.unit as [Quantite Existe]'+ 

        'from Article a '; 

enter image description here

正如你所看到的那樣,當一個表中有一個缺失記錄時,它會返回Null到DbGrid,因此我想用「0」替換缺失的記錄。 我試過這段代碼:

ADOQ.SQL.Text := 'select a.IdArt as [Code d''Article], '+ 
        'a.Nom,'+ 
        'Str(a.Prix)+" TND" as Prix, '+ 
        '(select Str(sum(QteEntree))+" "+a.unit from Stock where IdArt = a.IdArt group by IdArt) as [Quantite Entree],' + 
        '(select IIF(IsNull(sum(Qte)), "111" , Format(sum(Qte),"00.00")) from Sold where IdArt = a.IdArt group by IdArt) as [Quantite Vendu],'+ 
        'Str((select sum(QteEntree) from Stock where IdArt = a.IdArt group by IdArt) -' + 
        '(select sum(Qte) from Sold where IdArt = a.IdArt group by IdArt))+" "+a.unit as [Quantite Existe]'+ 

        'from Article a '; 

,但什麼都沒有改變,雖然這個代碼工作完美:

ADOQ.SQL.Text := 'Select a.IdArt,IIF((IsNull(s.qte)), "00,00" , Format((s.qte),"00.00")) from Article a left join sold s on s.IdArt = a.IdArt'; 

enter image description here

我在做什麼錯在這裏?

+2

請不要發佈數據圖片,與甚至是最未格式化的數據樣本相比,它們的用處甚少。樣本可以用來重現問題,但是沒有人會從圖片中輸入數據來測試它。 – Fionnuala

+0

您是否在Ms-Access中測試了上述查詢? – kobik

回答

0

確定找到了解決辦法:

iif(isnull((select sum(QteEntree) from Stock where IdArt = a.IdArt group by IdArt)) ,0, (select sum(QteEntree) from Stock where IdArt = a.IdArt group by IdArt)) 
0

嘗試取出「由IdArt組成的組件」 - 它們看起來沒有必要,因爲您已經排除了WHERE子句中的所有其他組件。

否則,這樣的事情可能是你如何寫你查詢的改進:

select 
    a.IdArt as [Code d''Article], 
    a.Nom, 
    Str(a.Prix)+" TND" as Prix, 
    Str(sum(stock.QteEntree))+" "+a.unit as [Quantite Entree], 
    IIF(IsNull(sum(sold.Qte)), "111" , Format(sum(sold.Qte),"00.00")) as [Quantite Vendu], 
    Str(sum(stock.QteEntree) - sum(sold.Qte))+" "+a.unit as [Quantite Existe] 

from Article a 
left join stock on a.IdArt = stock.IdArt 
left join sold on a.IdArt = sold.IdArt 
group by a.IdArt, a.Nom, a.Prix, a.unit 

您可能需要調整,雖然

其實,我更願意寫從上面這個說法:

IIF(IsNull(sum(sold.Qte)), "111" , Format(sum(sold.Qte),"00.00")) as [Quantite Vendu], 

喜歡這個:

Format(sum(IIF(IsNull(sold.Qte) , 0, sold.Qte)), "00.00") as [Quantite Vendu], 

Againt,我不是100%肯定會的工作,我只是在看你的函數的順序&邏輯

+0

格式化工作,但它導致我以前的問題:http://stackoverflow.com/questions/11337355/multiple-mysql-joins-with-aggregate-functions錯誤的結果... –