MySQL根据条件进行计数和求和

时间:2018-07-16 11:47:52

标签: mysql sql

是否有一种方法可以为每个PN计数SN并根据条件(在以下情况下为Loc)对它进行求和?

create table table1 (
            code int(10) primary key,
            PN varchar(10) not null,
        SN varchar(10) not null,
                Loc varchar(10));

insert into table1 values (1,'T1','a1','a');
insert into table1 values (2,'T1','a2','a');
insert into table1 values (3,'T1','a3','a');
insert into table1 values (4,'T1','a4','b');
insert into table1 values (5,'T1','a5','b');
insert into table1 values (6,'T1','a6','b');
insert into table1 values (7,'T2','a1','a');
insert into table1 values (8,'T2','a2','a');
insert into table1 values (9,'T2','a3','a');
insert into table1 values (10,'T2','a4','b');
insert into table1 values (11,'T2','a5','b');
insert into table1 values (12,'T2','a6','b');
insert into table1 values (13,'T2','a7','b');

我试图达到的结果是:

PN  a   b
T1  3   3
T2  3   4

3 个答案:

答案 0 :(得分:3)

这只是条件聚合:

select pn, sum(loc = 'a') as a, sum(loc = 'b') as b
from table1
group by pn;

如果您有loc个值的未知列表,则可能需要动态查询。 Google“ MySQL动态枢纽”。

答案 1 :(得分:1)

您可以使用条件聚合:

select PN, sum(case when Loc = 'a' then 1 else 0 end) as a,
           sum(case when Loc = 'b' then 1 else 0 end) as b
from table1 t1
group by PN; 

答案 2 :(得分:1)

您可以尝试这个

select PN, count(case when Loc = 'a' then 1 else null end) a,  count(case when Loc = 'b' then 1 else null end) b
from table1
group by PN