【问题标题】:Count group by, and add category for disabled计数分组,并为禁用添加类别
【发布时间】:2020-02-10 13:27:28
【问题描述】:

我有一张Automate 的表格,定义如下:

Colonne Type
id          int(11) Incrément automatique   
name        varchar(255)    
type        varchar(255)    
code        varchar(255)    
password    varchar(255)    
active      tinyint(1)

我为我的仪表板制作这样的视图:

SELECT COUNT('type') as count, type as name
FROM automate
GROUP BY type;

但这并不关心是否激活了自动化... 首先,我想从报告中删除未激活的自动化 (很容易添加一个简单的where activated = 1

但是我如何添加一个假的type 来计算未激活的自动化?

实际结果:

| type   | count |
| comx   |     4 |
| gateway|     3 |

想要的结果:

| type        | count |
| comx        |     1 |
| gateway     |     2 |
| unactivated |     4 |

(假设 type 来自枚举,并且 bdd 中不能有 unactivated 值)

【问题讨论】:

  • 。 .样本数据、所需结果和适当的数据库标签都会有所帮助。

标签: sql view group-by mariadb


【解决方案1】:

考虑使用条件聚合:

select
    type,
    count(*) cnt,
    sum(case when active = 1 then 1 else 0 end) activated,
    sum(case when active = 0 then 1 else 0 end) inactivated
from automate
group by type

对于每种类型,查询都会为您提供记录总数、active = 1 的记录数和active = 0 的记录数。


在您最终标记问题的 MariaDB 中,可以稍微简化查询:

select
    type,
    count(*) cnt,
    sum(active = 1) activated,
    sum(active = 0) inactivated
from automate
group by type

【讨论】:

    【解决方案2】:

    如果active只能取01的值,那么你可以使用:

    SELECT type, SUM(active) as num_active,
           SUM(1 - active) as num_inactive
    FROM automate
    GROUP BY type;
    

    如果要将它们添加为不同的行,则:

    SELECT type, COUNT(*) as num_active,
           SUM(1 - active) as num_inactive
    FROM automate
    WHERE active = 1
    GROUP BY type
    UNION ALL
    SELECT 'inactive', 0, COUNT(*)
    FROM automate
    WHERE active = 0;
    

    【讨论】:

    • 第二个请求无效:使用的 SELECT 语句的列数不同
    • @Andrelec1。 . .谢谢你。通过为活动添加0,这显然很容易解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    相关资源
    最近更新 更多