【问题标题】:Counting individual items in MY SQL or MS SQL column计算 MY SQL 或 MS SQL 列中的单个项目
【发布时间】:2020-04-14 16:22:06
【问题描述】:

我有列名为 Rule1 的数据,其值为 ..CorrectIncorrectUndefined

我能够使用 Group BY 在此特定列中获得它们的数量

select Rule1, count(*) from table_name group by Rule1;

我还有一列 Rule2,其值为 Correct,仅 Incorrect 当我尝试与上述类似的选择语句时,我得到了正确和不正确的唯一计数

我想让 Undefined 的计数为零,因为 Rule2 列中不存在 Undefined 如何做到这一点

如何编写需要在多列中显示固定值计数的查询

【问题讨论】:

  • 请告诉我们哪个答案对您有用。

标签: mysql sql group-by count


【解决方案1】:

您可以创建一个派生表,使用union all 枚举可能的值,然后使用left join 将您的表带入:

select x.rule1, count(t.rule1) cnt
from (select 'Correct' rule1 union all select 'Incorrect' union all select 'Undefined') x
left join mytable t on t.rule1 = x.rule1
group by x.rule1

这是一种跨数据库语法,适用于 MySQL 和 SQL Server。

在最新版本的 MySQL 中,您可以使用 values(row ...) 语法:

select x.rule1, count(t.rule1) cnt
from (values row('Correct'), row('Incorrect'), row('Undefined')) x(rule1)
left join mytable t on t.rule1 = x.rule1
group by x.rule1

在 SQL Server 中,等效查询是:

select x.rule1, count(t.rule1) cnt
from (values ('Correct'), ('Incorrect'), ('Undefined')) x(rule1)
left join mytable t on t.rule1 = x.rule1
group by x.rule1

【讨论】:

    【解决方案2】:

    你也可以像这样使用 sum:

    SELECT 
        sum(case when Rule1 = 'Correct' then 1 else 0 end) AS Rule1Correct,
        sum(case when Rule1 = 'Incorrect' then 1 else 0 end) AS Rule1Incorrect,
        sum(case when Rule1 = 'Undefined' then 1 else 0 end) AS Rule1Undefined,
        sum(case when Rule2 = 'Correct' then 1 else 0 end) AS Rule2Correct,
        sum(case when Rule2 = 'Incorrect' then 1 else 0 end) AS Rule2Incorrect  
    FROM 
        table_name 
    WHERE 
        1
    

    它在一个查询中启用多个计数。我添加了所有计数,认为前两个就足够了。

    此外,我不知道什么对服务器负载更好,这个或使用联合。

    【讨论】:

    • 这么好回答,埃里克?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多