Mysql 查询以计算按工厂的取件数量的不同计数

Mysql Query to calculate the distinct count of pickup numbers by plant

我正在尝试按工厂和取件月份年份获取取件数量的不同计数

输入

pickdate    picknumber  Plant
1/3/2022    L009803 Seattle
1/3/2022    L009803 Seattle
1/3/2022    L009803 Seattle
1/20/2022   L19033  Irving
1/21/2022   KL89231 Mini chih
1/23/2022   MY12341 kettle
1/23/2022   MY12341 kettle
1/25/2022   FD1211  Seattle
1/26/2022   HJ12W1  Irving
2/11/2022   K231245 Irving
2/11/2022   K231245 Irving
2/15/2022   N12ER1  Mini chih
2/21/2022   JS1234  Irving
2/25/2022   MK12E1  Kettle

我正在寻找下面的 table 以获取按工厂和时间段划分的取件数量的不同计数

Time period     Seattle Irving  Mini chih   Kettle
Jan-22              2     2        1           1
Feb-22              0     2        1           1

请找到输入的 DDL table..

create table input
(pickdate date,
picknumber varchar(40),
plant varchar(20))

insert into input values
('1/3/2022','L009803','Seattle'),
('1/3/2022','L009803','Seattle'),
('1/3/2022','L009803','Seattle'),
('1/20/2022','L19033','Irving'),
('1/21/2022','KL89231','Mini chih'),
('1/23/2022','MY12341','kettle'),
('1/23/2022','MY12341','kettle'),
('1/25/2022','FD1211','Seattle'),
('1/26/2022','HJ12W1','Irving'),
('2/11/2022','K231245','Irving'),
('2/11/2022','K231245','Irving'),
('2/15/2022','N12ER1','Mini chih'),
('2/21/2022','JS1234','Irving'),
('2/25/2022','MK12E1','Kettle')

有条件聚合:

SELECT DATE_FORMAT(pickdate, '%b-%y') Time_period,
       COUNT(DISTINCT CASE WHEN plant = 'Seattle' THEN picknumber END) Seattle,
       COUNT(DISTINCT CASE WHEN plant = 'Irving' THEN picknumber END) Irving,
       COUNT(DISTINCT CASE WHEN plant = 'Mini chih' THEN picknumber END) Mini_chih,
       COUNT(DISTINCT CASE WHEN plant = 'kettle' THEN picknumber END) kettle
FROM input
GROUP BY Time_period
ORDER BY STR_TO_DATE(CONCAT('01-', Time_period), '%d-%b-%y');

或者:

SELECT DATE_FORMAT(pickdate, '%Y-%m') Time_period,
       COUNT(DISTINCT CASE WHEN plant = 'Seattle' THEN picknumber END) Seattle,
       COUNT(DISTINCT CASE WHEN plant = 'Irving' THEN picknumber END) Irving,
       COUNT(DISTINCT CASE WHEN plant = 'Mini chih' THEN picknumber END) Mini_chih,
       COUNT(DISTINCT CASE WHEN plant = 'kettle' THEN picknumber END) kettle
FROM input
GROUP BY Time_period
ORDER BY Time_period;

参见demo