在SQL Server 查詢中將NULL 值替換為0
使用SQL 查詢時,經常會在某些欄位中遇到NULL 值,這會使資料處理和分析變得複雜。若要在 SQL Server 查詢中將 NULL 值替換為特定值(例如 0),可以使用 ISNULL 函數。
ISNULL 函數採用兩個參數:可能為空的列和替換值。在您的情況下,您希望將前三列(成功、失敗、取消)中的 NULL 值替換為 0。以下是實現此目的的方法:
SELECT ISNULL(column_name, 0) AS column_alias, ...
例如,要替換查詢的前三列為0,您可以按如下方式修改它:
SELECT ISNULL(c.rundate, 0) AS rundate, ISNULL(sum(case when c.runstatus = 'Succeeded' then 1 end), 0) AS Succeeded, ISNULL(sum(case when c.runstatus = 'Failed' then 1 end), 0) AS Failed, ISNULL(sum(case when c.runstatus = 'Cancelled' then 1 end), 0) AS Cancelled, count(*) AS Totalrun FROM ( SELECT a.name, CASE WHEN b.run_status = 0 THEN 'Failed' WHEN b.run_status = 1 THEN 'Succeeded' WHEN b.run_status = 2 THEN 'Retry' ELSE 'Cancelled' END AS Runstatus, CAST(SUBSTRING(CONVERT(VARCHAR(8), run_date), 1, 4) + '/' + SUBSTRING(CONVERT(VARCHAR(8), run_date), 5, 2) + '/' + SUBSTRING(CONVERT(VARCHAR(8), run_date), 7, 2) AS DATETIME) AS RunDate FROM msdb.dbo.sysjobs AS a(NOLOCK) INNER JOIN msdb.dbo.sysjobhistory AS b(NOLOCK) ON a.job_id = b.job_id WHERE a.name = 'AI' AND b.step_id = 0 ) AS c GROUP BY c.rundate
此修改後的查詢使用ISNULL 函數來確保即使前三列包含NULL 值,它們也會在用於計算或顯示在結果中之前被替換為0。
以上是如何在 SQL Server 查詢中將 NULL 值替換為 0?的詳細內容。更多資訊請關注PHP中文網其他相關文章!