MySQL数据库视图实现对某字段各值的统计

    技术2022-07-11  81

    Q:现在有一张now表,如下图 想统计某个时间点上,situation字段为1、2、3、4数据条数各有多少?

    A:新建视图,查询部分如下

    select `now`.`time` AS `time`, sum((case when (`now`.`situation` = 1) then 1 else 0 end)) AS `proportion1`, sum((case when (`now`.`situation` = 2) then 1 else 0 end)) AS `proportion2`, sum((case when (`now`.`situation` = 3) then 1 else 0 end)) AS `proportion3`, sum((case when (`now`.`situation` = 4) then 1 else 0 end)) AS `proportion4` from `now` group by `now`.`time` order by `now`.`time`

    查询结果如下图:

    Processed: 0.017, SQL: 9