计算具有特定列数的内容的行

时间:2013-04-30 13:30:39

标签: sql-server-2008 tsql count sum

我无法弄清楚如何使用包含其他列内容的行数来创建列。 不计算所有列(*)

-------------------------    Output should be (NO COLUMN D):    ---------
|  A  |  B  |  C  |  D  |                                       | Count |
-------------------------                                       ---------
| foo | foo | foo | foo |                                       |   9   |
-------------------------                                       ---------
| bar | bar | bar | bar |
-------------------------
|  x  |  x  |     |  x  |
-------------------------
|  y  |     |     |  y  |
-------------------------

我尝试了许多方法:

  • SELECT SUM(COUNT(A) + Count(B) + COUNT(C)) from SomeTable
  • SELECT COUNT(A + B + C)
  • SELECT COUNT(A,B,C)

我找不到正确的语法。有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:5)

SELECT SUM(CASE WHEN A IS  NULL THEN 0 ELSE 1 END) 
     + SUM(CASE WHEN B IS  NULL THEN 0 ELSE 1 END) 
     + SUM(CASE WHEN C IS  NULL THEN 0 ELSE 1 END) 
     AS [TOTAL]
FROM dbo.SomeTable

Demo

答案 1 :(得分:1)

遇到同样的错误昨天。这就是我解决它的方式。

Select Count(sum) from
(select 
count(A) as sum
from sometable
where ISNULL(A,'')<>''
,select 
count(B) as sum
from sometable
where ISNULL(B,'')<>''
,select 
count(C) as sum
from sometable
where ISNULL(C,'')<>''
)t