如何对至少包含X布尔1的行进行求和?

时间:2016-06-28 19:13:34

标签: sql sum boolean

示例表:

col1 col2 col3 col4
Abe  1    0    1
Bob  0    1    0
Cam  1    1    1
Dan  1    0    0
Eve  1    1    1

我如何查询以便SUM col1中有多少人共有2个1? (因此,由于Abe是唯一拥有2 1的人,因此查询输出数字1。)

感谢。

4 个答案:

答案 0 :(得分:2)

Select count(*) from table_name where col2+col3+col4=2

答案 1 :(得分:2)

在where子句中添加列并选择count()

 select count(*)
 from my_table 
 where CAST(ifnull(col2,false) AS SIGNED INTEGER) + 
       CAST(ifnull(col3,false) AS SIGNED INTEGER) +
       CAST(ifnull(col4,false) AS SIGNED INTEGER)  = 2;

答案 2 :(得分:2)

如果您的列值仅包含01,那么Vlad Călin BuzeascaisEdge答案将适用于您。但如果它可以不是01,那么你需要这个。

SELECT COUNT(*)
FROM Table_Name 
WHERE (CASE WHEN col2 = 1 THEN 1 ELSE 0 END) +
      (CASE WHEN col3 = 1 THEN 1 ELSE 0 END) +
      (CASE WHEN col4 = 1 THEN 1 ELSE 0 END) = 2

答案 3 :(得分:2)

;WITH cte AS (
    SELECT 'Abe' AS Col1, CAST(1 AS BIT) as Col2, CAST(0 AS BIT) as Col3, CAST(1 AS BIT) AS Col4
    UNION ALL
    SELECT 'Bob' AS Col1, CAST(0 AS BIT) as Col2, CAST(1 AS BIT) as Col3, CAST(0 AS BIT) AS Col4
    UNION ALL
    SELECT 'Cam' AS Col1, CAST(1 AS BIT) as Col2, CAST(1 AS BIT) as Col3, CAST(1 AS BIT) AS Col4
    UNION ALL
    SELECT 'AbeWNull' AS Col1, CAST(1 AS BIT) as Col2, CAST(NULL AS BIT) as Col3, CAST(1 AS BIT) AS Col4
)

SELECT *
FROM
    cte
WHERE
    ISNULL(CAST(Col2 AS INT),0) + ISNULL(Col3,0) + ISNULL(Col4,0) = 2

cte为您提供一些测试数据。 2件事。 1如果它是Booleanbit列,您可能需要cast/convertintegernumeric数据类型,其中至少有一列或添加不会工作。是的,我测试过并且需要。其次,如果你不处理null的潜力,你可能得不到你想要的答案。

例如。

SELECT 1 + NULL + 1

会给你NULL

在列上使用SUM并不相同,只会忽略nulls,但不会在添加行中忽略。