2013-07-01 84 views
-2

我有一張如下所示的表,如您所見,只有名稱列表。 有些人與其他人有相同的名字。我的目標是,用相同的'名字'來計算每個名字的總數,然後做一些條件如IF(total_of_firstname> = 1 & & total_of_firstname < = 20)。顯示結果。我如何才能使用MySQL來實現這一點?Mysql WHERE有條件

| id  | firstname  | lastname | 
|  1  | Bob   | Smith  | 
|  2  | Bob   | Marley  | 
|  3  | Stacey  | Clarke  | 
|  4  | Stacey  | Witson  | 
|  5  | Stacey  | Kowalowski | 
|  6  | George  | Benington | 
|  7  | George  | Robinson | 
+1

問題必須**證明正在解決這個問題的理解最小**。告訴我們你試圖做什麼,爲什麼它沒有工作,以及它應該如何工作。另請參閱:[堆棧溢出問題清單](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist) –

+0

你可以在這裏發佈上述數據集的預期重申嗎? – Salil

+0

我不知道如何做到這一點,這就是爲什麼我要求 – user2310422

回答

1

第一數據:

CREATE TABLE `table` 
(id int(11) auto_increment, 
    firstname text, 
    lastname text, 
    primary key (`id`) 
); 


INSERT INTO `table` SET 
firstname = 'a', 
lastname = 'b'; 

INSERT INTO `table` SET 
firstname = 'a', 
lastname = 'c'; 

INSERT INTO `table` SET 
firstname = 'b', 
lastname = 'c'; 

INSERT INTO `table` SET 
firstname = 'c', 
lastname = 'c'; 

INSERT INTO `table` SET 
firstname = 'a', 
lastname = 'c'; 

然後SQL:

SELECT tablegrouped.firstname, tablegrouped.firstnamecount 
FROM (
SELECT firstname, count(*) as firstnamecount 
FROM table 
GROUP BY firstname) AS tablegrouped 
WHERE tablegrouped.firstnamecount >=1 AND tablegrouped.firstnamecount <=20