繁体   English   中英

如何使用SQL计算特定行中值的数量?

[英]How can I count the number of a value in a particular row using SQL?

数据库

    id     decline     maintaining     losing
     1        true           false       true
     2       false           false      false
     3        true            true      false

我想使用SQL语句基于id计算真实值的数量。

如果这是所有列,则使用此列:

SELECT id,
       (case when decline = 'true' then 1 else 0 end) +
       (case when maintaining= 'true' then 1 else 0 end) +
       (case when losing= 'true' then 1 else 0 end) as HowMuchTrue
FROM YourTable
select sum(if(maintaining = 'true', 1, 0)) from table -- and here some conditions.

在MySQL中,如果是boolean字段,则可以将它们直接添加在一起:

SELECT id, decline + maintaining + losing
FROM mytable

在这里演示

这个问题似乎有点模糊,但我想我知道你要干什么。 对于每一行,您要计算“ true”在其中显示的次数。

为此,我们将使用CASE语句将true处理为1,将false处理为0。

SELECT
    id,
    CASE
    WHEN decline = 'true' THEN 1
    WHEN decline = 'false' THEN 0
    else 'check your logic'
    END as decline_processed,
    CASE
    WHEN maintaining = 'true' THEN 1
    WHEN maintaining = 'false' THEN 0
    else 'check your logic'
    END as maintaining_processed,
    CASE
    WHEN losing = 'true' THEN 1
    WHEN losing = 'false' THEN 0
    else 'check your logic'
    END as losing_processed
    FROM
    [table]

这为我们提供了以下结果:

id, decline_processed, maintaining_processed, losing_processed
1 , 1, 0, 1
2, 0, 0, 0
3, 1, 1, 0

从这里,我们可以获取结果并收集它们,并获得每一行的总和。

    SELECT
    id,
    SUM(query_result_alias.decline_processed 
+ query_result_alias.maintaining_processed 
+ query_result_alias.losing_processed
) as number_of_true_values
    FROM
    [query with case statement above] as query_result_alias
    GROUP BY
    query_result_alias.id

这将得到以下结果,我相信可以回答您的问题:

id, number_of_true_values
1, 2
2, 0
3, 2

奖励,我们可以将结果处理为摘要数据

SELECT
COUNT(query_result_alias2.id) as counter,
query_result_alias2.number_of_true_values
FROM
[query with case statement above] as query_result_alias2
GROUP BY
query_result_alias2.number_of_true_values

这样可以得到具有每个真值数量的行数:

counter, number_of_true_values
2, 2
1, 0

使用样本数据,您将只有两个结果,但是较大的数据集将提供所有选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM