zoukankan      html  css  js  c++  java
  • mysql如何分类统计数量

    比如我表test里面有id,mc,xh三个字段(分别是自动编号,钢材名称(若干种),钢材型号(大号,中号,小号))

    id    mc            xh   
    1    钢管          大号
    2    铜管          大号
    3    铁管          小号
    4    铝管          中号
    5    钢管          小号

    我现在要分别统计出“mc”里面的各种型号的东西有多少。意思是:
    我要统计钢管,铜管,铁管,铝管的大,中,小号各有多少条记录。

    并且mc里面的是不固定的,可能还有金管,还有熟料管什么的,,但是xh里面只有三种情况,那就是大号,中号,小号:

    1.在mysql中建立一个测试数据表

    CREATE TABLE `tb_test_count` (
      `id` bigint(20) NOT NULL,
      `mc` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL,
      `xh` varchar(255) CHARACTER SET utf8mb4 DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    2.插入一批数据

    INSERT INTO tb_test_count VALUES(1,'钢管','大号');
    INSERT INTO tb_test_count VALUES(2,'铜管','大号');
    INSERT INTO tb_test_count VALUES(3,'铁管','小号');
    INSERT INTO tb_test_count VALUES(4,'铝管','大号');
    INSERT INTO tb_test_count VALUES(5,'铝管','小号');
    INSERT INTO tb_test_count VALUES(6,'钢管','大号');
    INSERT INTO tb_test_count VALUES(7,'钢管','小号');

    3.查询统计的SQL语句

    select mc,count(case when xh='大号' then 1 end) as 大号,
    count(case when xh='中号' then 1 end) as 中号,
    count(case when xh='小号' then 1 end) as 小号
    from tb_test_count
    group by mc

    4.查询结果截图如下:

     5.如果使用sum方法查询则(当数据一条都不存在的时候查询出来的结果是null)

    select mc,sum(case when xh='大号' then 1 end) as 大号,
    sum(case when xh='中号' then 1 end) as 中号,
    sum(case when xh='小号' then 1 end) as 小号
    from tb_test_count
    group by mc

    当一个表中需要统计某个字段中不同类型的数据条数的时候,可以使用该方法。

  • 相关阅读:
    nowcoderD Xieldy And His Password
    Codeforces681D Gifts by the List
    nowcoder80D applese的生日
    Codeforces961E Tufurama
    Codeforces957 Mahmoud and Ehab and yet another xor task
    nowcoder82E 无向图中的最短距离
    nowcoder82B 区间的连续段
    Codeforces903E Swapping Characters
    Codeforces614C Peter and Snow Blower
    Codeforces614D Skills
  • 原文地址:https://www.cnblogs.com/lr393993507/p/9791907.html
Copyright © 2011-2022 走看看