现在我想计算列包含值或不为null的行。我是SQL的初学者;我的SQL查询如下:
select count(news) AS news_count, count(`msg`) as msg_count , count('req') as req_count
from news_msg_activity
where news!=''
UNION
select count(news) AS news_count, count(`msg`) as msg_count , count('req') as req_count
from news_msg_activity
where msg!=''
UNION
select count(news) AS news_count, count(`msg`) as msg_count , count('req') as req_count
from news_msg_activity
where req!=''
当我运行查询时,它会在结果中给出两个数字。但我需要一个数字结果,它将计算上述操作中的记录数。我不知道如何编写该查询。有人能帮助我吗?
但我需要
news_count || msg_count || req_count
2 || 2 || 3
答案 0 :(得分:2)
将查询包装在子查询中。
SELECT * -- here you can sum, count or whatever elese you need
FROM (
-- your query goes here
) as src
或者只是
select
sum(news!='') AS news_count
, sum( msg!='' ) as msg_count
, sum(req!='') as req_count
from news_msg_activity
as boolean语句将整数计算为0/1(false / true) - 这将作为满足条件的计数。
答案 1 :(得分:2)
COUNT(column)
已经返回非空记录的数量,因此,除非我误解了您尝试做的事情,否则您可以更加简单。以下查询应返回每个字段的非空记录数:
select count(news) AS news_count
, count(`msg`) as msg_count
, count(req) as req_count
from news_msg_activity
如果你担心的是从计数中删除空字符串,你可以使用NULLIF
函数:
select count(nullif(news, '')) AS news_count
, count(nullif(`msg`, '')) as msg_count
, count(nullif(req, '')) as req_count
from news_msg_activity
答案 2 :(得分:0)
你确定你真的需要UNION吗?也许是这样的?
SELECT
*
FROM
(SELECT
count(news) AS news_count
FROM
news_msg_activity
WHERE
news!= '') a,
(SELECT
count(msg) as msg_count
FROM
news_msg_activity
WHERE
msg!= '') b,
(SELECT
count(req) as req_count
FROM
news_msg_activity
WHERE
req!= '') c
此外,在表的方案中创建字段news, msg, req
- NOT NULL。因为现在count()计算具有字段空值的行。您可以添加IS NOT NULL
进行查询,但更好的解决方案是在表格的方案中设置NOT NULL并设置默认值。这将使你免于错误"将来。