2在单个查询中分组

时间:2017-02-12 12:26:45

标签: mysql sql database

tbl
A | B

A包含许多值。 B只包含2个值。

我希望将数据作为

a1 | count(b1) | count(b2)
a2 | count(b1) | count(b2)
....
an | count(b1) | count(b2)

2 个答案:

答案 0 :(得分:3)

希望,我理解你的问题,

试图创造同样的问题。请参考以下查询。

同一http://sqlfiddle.com/#!9/b557543/4/0

的Sqlfiddle链接
CREATE TABLE SO_TEST(
COL1 VARCHAR(100),
COL2 VARCHAR(100)
);

INSERT INTO SO_TEST VALUES('V1','Y');
INSERT INTO SO_TEST VALUES('V1','N');
INSERT INTO SO_TEST VALUES('V2','Y');
INSERT INTO SO_TEST VALUES('V2','N');
INSERT INTO SO_TEST VALUES('V3','Y');
INSERT INTO SO_TEST VALUES('V4','Y');

select col1 , 
count(case when col2='Y' then 1 end) y_cnt,
count(case when col2='N' then 1 end) n_cnt
from SO_TEST
group by col1;

enter image description here

答案 1 :(得分:2)

应该如此简单:

select
a,
count(case when b = b1 then 1 else null end) as b1,
count(case when b = b2 then 1 else null end) as b2
from tbl
group by a