3

我有一个表和表中的 5 列。我想要列值不为空的每一列的行数。

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

我应该得到像 3,2,5,4,2 这样的输出

4

5 回答 5

6

提供的解决方案对我不起作用。我不得不修改代码如下:

SELECT 
COUNT(NULLIF(Column1,'')),
COUNT(NULLIF(Column2,'')),
COUNT(NULLIF(Column3,'')),
COUNT(NULLIF(Column4,'')),
COUNT(NULLIF(Column5,''))
FROM Table1
于 2016-08-03T16:04:45.977 回答
5

像这样的东西怎么样

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

SQL 小提琴演示

COUNT(expr)

返回 SELECT 语句检索的行中 expr 的非 NULL 值的计数。

COUNT(*) 有点不同,它返回检索到的行数的计数,无论它们是否包含 NULL 值。

于 2013-08-08T07:03:19.090 回答
2

根据COUNT()函数参考,它只计算非NULL项目。所以,

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

应该返回你想要的信息。

于 2013-08-08T07:22:34.003 回答
2

我支持上述响应 - 只需确保字段名称当然按照它们在两个区域中的顺序匹配。

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
于 2017-04-07T14:15:07.970 回答
0

您可以使用子查询:

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
于 2013-08-08T07:06:32.320 回答