[英]SQL statement: How to get a special output for NULL value in aggregate function?
+------+
| num |
+------+
| 1 |
| 2 |
| 3 |
| NULL |
| 5 |
| 6 |
+------+
这是表测试。
select max(num) from test; ---> 6
如何编写一条如果存在NULL值的SQL语句->输出应为“ OK”
如果此列中不存在NULL值->输出应为6
我尝试了很多次但没有运气。 有什么帮助吗? 如果解决方案是ANSI SQL,那就太好了
试试这个: http : //www.sqlfiddle.com/#!2/dfcbd/2
这个:
CREATE TABLE tbl
(`num` int);
INSERT INTO tbl
(`num`)
VALUES
(1),
(2),
(3),
(NULL),
(5),
(6);
select if(bit_or(num is null), 'OK', max(num)) as max from tbl;
输出:
OK
这个:
CREATE TABLE tblx
(`num` int);
INSERT INTO tblx
(`num`)
VALUES
(1),
(2),
(3),
(5),
(6);
select if(bit_or(num is null), 'OK', max(num)) as max from tblx;
输出:
6
http://www.sqlfiddle.com/#!1/679b2/1下的 ANSI SQL
大多数数据库没有一流的布尔类型,因此查询时间更长。 和许多数据库一样,不要将整数隐式转换为varchar
select
case when count(case when num is null then 1 end) > 0 then
'OK'
else
cast(max(num) as varchar(16))
end
from tbl
如果每个数据库都具有一流的布尔值,则可以将以上内容简化为:
select
case when sum(cast( (num is null) as int )) > 0 then
'OK'
else
cast(max(num) as varchar(16))
end
from tbl
尽管如果每个数据库上确实都有一个一流的布尔值,它们也会生成bool_or / bit_or,并且它更短: http ://www.sqlfiddle.com/#!1/679b2/6
select
case when bool_or( num is null ) then
'OK'
else
cast(max(num) as varchar(16))
end
from tbl;
由于COUNT(column)
打折空值,因此您可以使用:
SELECT CASE WHEN COUNT(*) = COUNT(num) THEN MAX(num) ELSE "OK" END
FROM Test;
我使用的DBMS(Informix)要求THEN和ELSE中的类型相同,因此我进行了测试:
SELECT CASE WHEN COUNT(*) = COUNT(num) THEN CAST(MAX(num) AS CHAR(10)) ELSE "OK" END
FROM Test;
这是冗长的强制转换方式之一(但它是标准SQL)。 在给定的DBMS中通常有速记。
输出示例:
+ CREATE TABLE Test(Num INTEGER);
+ INSERT INTO Test VALUES(1);
+ INSERT INTO Test VALUES(2);
+ INSERT INTO Test VALUES(3);
+ INSERT INTO Test VALUES(NULL);
+ INSERT INTO Test VALUES(5);
+ INSERT INTO Test VALUES(6);
+ SELECT CASE WHEN COUNT(*) = COUNT(num) THEN CAST(MAX(num) AS CHAR(10)) ELSE "OK" END
FROM Test;
OK
+ DELETE FROM Test WHERE Num IS NULL;
+ SELECT CASE WHEN COUNT(*) = COUNT(num) THEN CAST(MAX(num) AS CHAR(10)) ELSE "OK" END
FROM Test;
6
在我的SQL中
Select (Case When hasNull > 0 Then 'OK' Else mx End) As Result
From
(
Select Max(num) as mx,Sum(Case When numIs Null Then 1 Else 0 End) as hasNull
From test
) as t
尝试这个..
select CASE num when num is null then "OK" else max(num) END from test;
尝试这个
select
case when ( select COUNT(*) from tableName where num is null ) > 0 then 'OK'
else CONVERT(varchar, MAX(num) ) end as [num]
from tableName
如果要避免运行两个查询(一个用于测试NULL
值,然后一个用于计算max
,则可以使用count(*)
和count(num)
来计算带有和不带有NULL
值的值的数量,例如(SQL Server语法):
with TestQ as
(
select max(num) as MaxNum, count(num) as NumCountNotNull, count(*) as NumCountTotal from nullAggTest
)
select
SpecialMax = case
when NumCountNotNull < NumCountTotal then -1
else MaxNum
end
from TestQ
请注意,为简单起见,我将您的特殊值OK
替换为-1
,否则您需要强制转换一点:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.