COUNT条件为真的列数? SQL Server 2008 R2

时间:2014-01-08 10:16:33

标签: sql sql-server-2008 tsql sql-server-2008-r2

我有一张类似

的表格
ID Col1 Col2 Col3 Col4
1  3     5    3    3   

我想要做的是计算此特定行中3的数量。

我试过了

select COUNT(*) 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'TableName'   -- but obviously I need WHERE Col1 = 3 OR Col2 = 3...

实现这一目标的最佳方式是什么?

3 个答案:

答案 0 :(得分:2)

根据OP的要求,可以做到这一点

select 
CASE WHEN Col1 = 3 then 1 ELSE 0 END +
CASE WHEN Col2 = 3 then 1 ELSE 0 END +
CASE WHEN Col3 = 3 then 1 ELSE 0 END +
CASE WHEN Col4 = 3 then 1 ELSE 0 END
From TableName

答案 1 :(得分:2)

我真的不喜欢使用PIVOT这样的解决方案使用APPLY。

SELECT
    T.id
    , Val
    , COUNT(*)
FROM MyTable AS T
CROSS APPLY (
    VALUES
        (T.C1)
        , (T.C2)
        , (T.C3)
        , (T.C4)
) AS X(Val)
GROUP BY T.Id, X.Val
ORDER BY T.Id, X.val

答案 2 :(得分:0)

请找到示例代码:

            DECLARE @Query VARCHAR(MAX) = 'SELECT Count = '
        SELECT 
        @Query += '( CASE WHEN '+ COLUMN_NAME + ' = 3 THEN 1 ELSE 0 END ) + ' 
        FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TEST' AND COLUMN_NAME <> 'ID'
        SET @Query = SUBSTRING(@Query, 1, DATALENGTH(@Query) - 2) + ' FROM TEST WHERE ID = 1'
        EXEC(@Query)