比如我表test里面有id,mc,xh三個(gè)字段(分別是自動(dòng)編號(hào)臀脏,鋼材名稱(chēng)(若干種),鋼材型號(hào)(大號(hào),中號(hào)逼友,小號(hào)))
id mc xh
1 鋼管 大號(hào)
2 銅管 大號(hào)
3 鐵管 小號(hào)
4 鋁管 中號(hào)
5 鋼管 小號(hào)
我現(xiàn)在要分別統(tǒng)計(jì)出“mc”里面的各種型號(hào)的東西有多少精肃。意思是:
我要統(tǒng)計(jì)鋼管,銅管帜乞,鐵管司抱,鋁管的大,中黎烈,小號(hào)各有多少條記錄习柠。
并且mc里面的是不固定的,可能還有金管照棋,還有熟料管什么的资溃,,但是xh里面只有三種情況烈炭,那就是大號(hào)溶锭,中號(hào),小號(hào):
1.在mysql中建立一個(gè)測(cè)試數(shù)據(jù)表
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.插入一批數(shù)據(jù)
INSERT INTO tb_test_count VALUES(1,'鋼管','大號(hào)');
INSERT INTO tb_test_count VALUES(2,'銅管','大號(hào)');
INSERT INTO tb_test_count VALUES(3,'鐵管','小號(hào)');
INSERT INTO tb_test_count VALUES(4,'鋁管','大號(hào)');
INSERT INTO tb_test_count VALUES(5,'鋁管','小號(hào)');
INSERT INTO tb_test_count VALUES(6,'鋼管','大號(hào)');
INSERT INTO tb_test_count VALUES(7,'鋼管','小號(hào)');
3.查詢(xún)統(tǒng)計(jì)的SQL語(yǔ)句
select mc,count(case when xh='大號(hào)' then 1 end) as 大號(hào),
count(case when xh='中號(hào)' then 1 end) as 中號(hào),
count(case when xh='小號(hào)' then 1 end) as 小號(hào)
from tb_test_count
group by mc
4.查詢(xún)結(jié)果如下
5.在限定條件下分類(lèi)查詢(xún)
如符隙,限定入廠時(shí)間內(nèi)的分類(lèi)查詢(xún)暖途;
5.1增加一個(gè)入廠時(shí)間字段time
5.2查詢(xún)1月份統(tǒng)計(jì)的SQL語(yǔ)句
select mc,count(case when xh='大號(hào)' then 1 end) as 大號(hào),
count(case when xh='中號(hào)' then 1 end) as 中號(hào),
count(case when xh='小號(hào)' then 1 end) as 小號(hào)
from (select * FROM tb_test_count where time <"2021-02-01" AND time>"2020-12-31")tb1
group by mc
5.3 查詢(xún)結(jié)果如下