我有下面提到的表:
其中Val
列有3个不同的值a,b&角
ID Val
1 a
1 a
1 b
2 b
2 c
2 c
3 c
我想得到各个Val
值(即a,b& c)的唯一ID和id数。
我正在使用这样的查询,但它有助于我一次识别单个Val
值的计数。
SELECT ID,COUNT(*)
FROM table1
WHERE Val='c' GROUP BY ID;
必需的输出:
ID count a b c
1 3 2 1 0
2 3 0 1 2
3 1 0 0 1
答案 0 :(得分:1)
只需使用条件聚合:
select id, count(*), sum(val = 'a') as a, sum(val = 'b') as b, sum(val = 'c') as c
from table1
group by id;
答案 1 :(得分:1)
当val等于a,b或c时,您可以使用group by并对计数求和。见下文:
select id,
count(*) as `count`,
sum(case when val = 'a' then 1 else 0 end) as a,
sum(case when val = 'b' then 1 else 0 end) as b,
sum(case when val = 'c' then 1 else 0 end) as c
from yourTable
group by id;