Bre*_*Bim 88 mysql sql t-sql sql-server sql-server-2008
我有一个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'
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我希望Quantity和RegularPrice默认为零.
Mic*_*ren 127
这很简单
IsNull(FieldName, 0)
Run Code Online (Sandbox Code Playgroud)
或者更完整:
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'
Run Code Online (Sandbox Code Playgroud)
小智 7
如果是MySQL或SQLite,正确的关键字是IFNULL(not 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'
Run Code Online (Sandbox Code Playgroud)
COALESCE(field, 'default')
Run Code Online (Sandbox Code Playgroud)
例如:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Run Code Online (Sandbox Code Playgroud)
另外,您可以使用多列NULL通过COALESCE函数检查它们。例如:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96798 次 |
| 最近记录: |