2009-11-02 97 views
64

我有一個Microsoft SQL Server 2008查詢使用左外連接從三個表中返回數據。很多時候,第二個和第三個表中都沒有數據,所以我得到一個null,我認爲它是左外連接的默認值。有沒有辦法在select語句中替換默認值?我有一個解決方法,我可以選擇一個表變量,但感覺有點骯髒。替換從左外連接返回的默認空值

SELECT iar.Description, iai.Quantity, iai.Quantity * rpl.RegularPrice as 'Retail', 
iar.Compliance FROM InventoryAdjustmentReason iar 
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId) 
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId) 
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo) 
WHERE iar.StoreUse = 'yes' 

我希望數量和RegularPrice默認爲零,如果可能的話。

回答

102

這是那麼容易,因爲

IsNull(FieldName, 0) 

或者更徹底:

SELECT iar.Description, 
    ISNULL(iai.Quantity,0) as Quantity, 
    ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
    iar.Compliance 
FROM InventoryAdjustmentReason iar 
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId) 
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId) 
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo) 
WHERE iar.StoreUse = 'yes' 
+3

我知道這一定很容易,但由於某種原因,我被阻止如何做到這一點。謝謝。 –

+29

如果是MySQL,則應將IsNull替換爲'IFNULL'。謝謝。 – Dhanushka

+10

在PostgreSQL中,它似乎是[「COALESCE」](http://www.postgresql.org/docs/9.3/static/functions-conditional.html)。對於MySQL,手冊頁在這裏:[「IFNULL」](http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html)。不知道標準。 –

0

不是他ISNULL,在此IFNULL。

SELECT iar.Description, 
     IFNULL(iai.Quantity,0) as Quantity, 
     IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
     iar.Compliance 
    FROM InventoryAdjustmentReason iar 
    LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId) 
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId) 
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo) 
WHERE iar.StoreUse = 'yes'