我有一个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'
如果可能,我希望Quantity和RegularPrice默认为零。
答案 0 :(得分:122)
这就像
一样简单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'
答案 1 :(得分:5)
如果SQLite
或IFNULL
正确的关键字为 ISNULL
(不是 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'
)。
{{1}}
答案 2 :(得分:2)
COALESCE(field, 'default')
例如:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
table t
LEFT JOIN
detail d ON t.id = d.item
此外,您可以使用多列通过COALESCE函数来检查其NULL
。
答案 3 :(得分:0)
对于 Oracle,您可以使用:
NVL(columnName,deafultValue)
:- NVL 用于将查询输出中的空值转换为默认值。例如。如果你想用“NA”替换空值,那么使用这样的东西。
SELECT NVL(columnName,'NA') FROM tableName