问题
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