【问题标题】:Sql Count rows which contains some valueSql Count 包含一些值的行
【发布时间】:2015-04-03 13:10:46
【问题描述】:

现在我想计算列包含值或不为空的行数。我是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

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    将您的查询包装在子查询中。

    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 
    

    作为布尔语句将整数计算为 0/1(假/真) - 这充当满足条件的计数。

    检查小提琴:http://sqlfiddle.com/#!9/8c780/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
      

      【讨论】:

      • last column count('req') as req_count not working..它计算所有行
      • 哦,对了,对不起。我只是复制了您的语法而没有考虑它,但是您不能使用单引号来转义字段名称。它只是被解释为一个常数。试试我编辑的版本。
      【解决方案3】:

      你确定你真的需要 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。这将使您免于将来出现“错误”。

      【讨论】:

        猜你喜欢
        • 2021-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 2020-12-14
        • 2020-07-22
        • 1970-01-01
        相关资源
        最近更新 更多