2012-11-19 28 views
0

的計數這裏是我的表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中使用它)。 我會很感激任何關於這個問題的意見。

+0

第一個答案是,你需要爲您透視圖..例如[SQLFiddle](http://sqlfiddle.com/#!2/d4131/7) – bonCodigo

回答

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

與where子句

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

但我想使用這種「顏色像'%bl%',像'%ree%',就像%ed%」在我的查詢。任何輸入 –

+0

您可以添加條件在上述查詢與條件 – AnandPhadke

+0

所有條件,請你在你的答案解釋。 –

0

可以使用

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