Get each column count where column value is not NULL

二次信任 提交于 2021-02-04 19:08:33

问题


I have a table and 5 columns in the table. I want row count for each column where column value is not null.

column1 column2 column3 column4 column5
1        2        2       2        2
2        2        2       NULL     2     
3        NULL     2       2        NULL
NULL     NULL     2       2        NULL
NULL     NULL     2       2        NULL

i should get output like 3,2,5,4,2


回答1:


How about something like

SELECT 
COUNT(Column1),
COUNT(Column2),
COUNT(Column3),
COUNT(Column4),
COUNT(Column5)
FROM Table1

SQL Fiddle DEMO

From COUNT(expr)

Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement.

COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values.




回答2:


The solutions offered did not work for me. I had to modify the code as follows:

SELECT 
COUNT(NULLIF(Column1,'')),
COUNT(NULLIF(Column2,'')),
COUNT(NULLIF(Column3,'')),
COUNT(NULLIF(Column4,'')),
COUNT(NULLIF(Column5,''))
FROM Table1



回答3:


According to the COUNT() function reference, it just counts non-NULL items. So,

SELECT
  COUNT(column1) AS column1,
  COUNT(column2) AS column2,
  COUNT(column3) AS column3,
  COUNT(column4) AS column4,
  COUNT(column5) AS column5
FROM yourtable;

should return you the information you want.




回答4:


I second that above response - just make sure the field names match of course in the order they are in in both areas.

select column1, column2, column3, column4, column5

from ( select

  sum(column1 is not null) as column1,

  sum(column2 is not null) as column2,

  sum(column3 is not null) as column3,

  sum(column4 is not null) as column4,

  sum(column5 is not null) as column5

from mytable) x



回答5:


You can use a subquery:

select column1, column2, column3, column4, column5
from ( select
  sum(column1 is not null) as column1,
  sum(column2 is not null) as column2,
  sum(column3 is not null) as column3,
  sum(column4 is not null) as column4,
  sum(column5 is not null) as column5
from mytable) x


来源:https://stackoverflow.com/questions/18119798/get-each-column-count-where-column-value-is-not-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!