SELECT max(x)返回null; 我怎样才能让它返回0?

运行以下命令时,如何返回0而不是null:

SELECT MAX(X) AS MaxX FROM tbl WHERE XID = 1 

(假设XID = 1时没有行)

在SQL 2005/2008中:

 SELECT ISNULL(MAX(X), 0) AS MaxX FROM tbl WHERE XID = 1 

要么:

 SELECT coalesce(MAX(X), 0) AS MaxX FROM tbl WHERE XID = 1 

像这样(对于MySQL):

 SELECT IFNULL(MAX(X), 0) AS MaxX FROM tbl WHERE XID = 1 

对于MSSQL,用ISNULLreplaceIFNULL ,或者用OraclereplaceNVL

你也可以使用COALESCE(expression [,… n]) – 返回第一个非null,如:

 SELECT COALESCE(MAX(X),0) AS MaxX FROM tbl WHERE XID = 1 

甲骨文会

 SELECT NVL(MAX(X), 0) AS MaxX FROM tbl WHERE XID = 1; 

对于OLEDB,你可以使用这个查询:

 select IIF(MAX(faculty_id) IS NULL,0,MAX(faculty_id)) AS max_faculty_id from faculties; 

由于IFNULL不在那里工作

取决于你使用的是什么产品,但大多数支持类似的东西

 SELECT IFNULL(MAX(X), 0, MAX(X)) AS MaxX FROM tbl WHERE XID = 1 

要么

 SELECT CASE MAX(X) WHEN NULL THEN 0 ELSE MAX(X) FROM tbl WHERE XID = 1