计算表中的几乎所有fieds都有0值的行。数据库SQL Server

时间:2015-10-30 11:32:11

标签: sql sql-server

我的表格包含50个字段,名称为Sti_01,Sti_02,Sti_03,...,Sti_50。

举个例子:

 ColumnID | YEAR | Sti_01 | Sti_02 | ... | Sti_50 
----------+------+--------+--------+-----+-------
 1        | 2015 |   0    |  0     |  0  |   0
 2        | 2014 |   45   |  0     |  5  |   0
 3        | 2014 |   0    |  0     |  0  |   0
 4        | 2015 |   0    |  0     |  0  |   0 
 5        | 2014 |   67   |  2     |  3  |   0  

我需要计算所有Sti_XX列都有0值的行 - 在我们的示例行中,ColumnID为1,3和4.答案将是3.

2 个答案:

答案 0 :(得分:1)

为什么不明确过滤每个列值?

select count(*)
from table_name
where Sti_01 = 0
and Sti_02 = 0
...
and Sti_50 = 0

或者,如果您更喜欢水平代码布局

select count(*)
from table_name
where (Sti_01, Sti_02, ... , Sti_50) in 
((0,0,...,0))

答案 1 :(得分:1)

糟糕的桌子设计!无论如何:

WITH  unpivoted
        AS (
             SELECT ColumnID, Sti, [Value]
             FROM   ( SELECT  * FROM MyTable ) AS p 
             UNPIVOT  ( [value] FOR Sti IN 
                ( [Sti_01], [Sti_02], ..., [Sti_50] ) ) AS unpvt
           )
  SELECT  columnId
  FROM    unpivoted
  GROUP BY columnId
  HAVING  SUM([Value]) = 0;