如何计算非空字段?

时间:2016-09-01 06:47:41

标签: mysql sql

我需要得到值不为空的字段数。

我的表

   city      id_no  no1    no2    no3
   chn       A12    2158
   chn       A13    8181   8182  8183
   chn       A14    19138

我需要为no1,...,no3

设置字段数

我的查询

SELECT 
  count(id_no) as total_id,
  (count(no1) +
    count(no2) +
    count(no3)) as c_count
FROM table 
  WHERE city='chn';

我的输出

  total_id      c_count
  3             9

预期:

  total_id      c_count
  3             5

我期待5而不是9,因为5个字段不为空。

5 个答案:

答案 0 :(得分:0)

SELECT 
count(id_no) as total_id,
(case when count(no1)='' or count(no1) is null then 0 else count(no1) end +
    case when count(no2)='' or count(no2) is null then 0 else count(no2) end +
    case when count(no3)='' or count(no3) is null then 0 else count(no3) end +
    case when count(no4)='' or count(no4) is null then 0 else count(no4) end +
    case when count(no5)='' or count(no5) is null then 0 else count(no5) end +
    case when count(no6)='' or count(no6) is null then 0 else count(no6) end +
    case when count(no7)='' or count(no7) is null then 0 else count(no7) end +
    case when count(no8)='' or count(no8) is null then 0 else count(no8) end  +
    case when count(no9)='' or count(no9) is null then 0 else count(no9) end +
    case when count(no10)='' or count(no10) is null then 0 else count(no10) end
     ) as c_count
    FROM table 
    WHERE city='chn';

答案 1 :(得分:0)

我正在获得您想要的相同输出请点击这里我提供我的截图   My Output

答案 2 :(得分:0)

SELECT count(id_no) as total_id,
        count(CASE WHEN `nol`!="" THEN 1 END) as no1 
 FROM `table` where city='chn'

试试这个

答案 3 :(得分:0)

或者你可以简单地这样做以避免NULL或''数据

SELECT 
  count(id_no) as total_id,
  (count(CASE WHEN no1 > 0 THEN no1 ELSE NULL END) +
   count(CASE WHEN no2 > 0 THEN no2 ELSE NULL END) +
   count(CASE WHEN no3 > 0 THEN no3 ELSE NULL END)) as c_count
FROM table 
WHERE city='chn';

答案 4 :(得分:0)

select count(distinct a.`id_no`),count(*) from 
(
  select `id_no`,`no1` as `non`  from table WHERE city='chn'
  union all
  select `id_no`,`no2` as `non`  from table WHERE city='chn'
  union all
  select `id_no`,`no3` as `non`  from table WHERE city='chn'
)a where a.`non` is not null