从列中搜索以获取各种数据的计数

时间:2012-11-19 12:23:11

标签: java mysql jdbc

这是我的表emp

+---------+------------------+
| emp     |  id      | color |
+---------+------------------+
| hary    | 123      |  red  |
+---------+------------------+
| lary    | 125      | green |
+---------+------------------+
| gary    | 038      |  red  |
+---------+------------------+
| Kris    | 912      | blue  |
+---------+------------------+
| hary    | 123      |  red  |
+---------+------------------+
| Ronn    | 334      | green |
+---------+------------------+

现在我想找出每种颜色的数量,即红色,绿色和蓝色;

在这种情况下,我试图用where color like '%bl%',like '%ree%',like %ed%.来写下查询并想要这个结果

+--------------------------+
| red | blue | green       |
+--------------------------+
|   3 |   1  |  2          | 
+--------------------------+

我试过这件事:

    select count(case when color='green' then 1 end) as Green,count(case when 
color='blue' then 1 end) as Blue,count(case when color='Red' then 1 end) as Red from emp;

我不想对其名称进行硬编码(因为我将在我的代码jdbc中使用它)。 我很感激有关此问题的任何意见。

2 个答案:

答案 0 :(得分:3)

select color,count(*) clrCount
from emp 
group by color

with where子句

select color,count(*) clrCount
from emp where (color like '%bl%' or color like '%ree%')
group by color

答案 1 :(得分:0)

您可以使用

select color,count(*) from emp group by color;