SELECT max(x)返回null;怎么能让它返回0?

时间:2009-11-06 16:31:38

标签: sql sql-server

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

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

(假设没有XID = 1的行)

7 个答案:

答案 0 :(得分:90)

或:

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

答案 1 :(得分:66)

在SQL 2005/2008中:

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

答案 2 :(得分:25)

像这样(对于MySQL):

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

对于MSSQL,将IFNULL替换为ISNULL,或者将Oracle替换为NVL

答案 3 :(得分:10)

你也可以使用COALESCE(表达式[,... n]) - 首先返回非null,如:

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

答案 4 :(得分:5)

Oracle将是

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

答案 5 :(得分:4)

对于OLEDB,您可以使用此查询:

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

因为IFNULL不在那里工作

答案 6 :(得分:2)

取决于您使用的产品,但大多数支持

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