2014-10-29 91 views
0

嗨occurances什麼,我需要做的是創造,輸出的第一個字符的總和一個字段的表中的SELECT語句,因此輸出會看起來像的MySQL選擇第一個字母字符

A,12 
B,0 
C,20 
D,14 
E,0 
ect... 
的總和

的表稱爲接觸,在上面有12次出現的人,他們的名字以字母A和有字母B的0出現次數

我希望我已經解釋了這種正確

回答

0

爲了使結果顯示丟失的信件,你需要手動生成所有的字母(例如使用子查詢)

SELECT a.Letter, 
     COUNT(u.Name) AS TotalCount 
FROM 
     (
      SELECT 'A' Letter UNION ALL 
      SELECT 'B' Letter UNION ALL 
      SELECT 'C' Letter UNION ALL 
      -- until Z 
      SELECT 'Z' Letter 
     ) AS a 
     LEFT JOIN userList u 
      ON a.Letter = LEFT(u.Name, 1) -- <== column name 
GROUP BY a.Letter 
ORDER BY a.Letter 
+0

謝謝,但我如何添加一個where子句的用戶列表,但仍然保持零字母,我試着添加在哪裏u.verified = 1和B disapears – cghrmauritius 2014-10-29 08:56:12

+0

你應該將它添加到'ON'子句。例如'ON a.Letter = LEFT(u.Name,1)AND u.verified = 1' – 2014-10-29 09:10:08

0

試試這個:

select substr(name, 1,1), count(*) from contacts group by substr(name, 1,1) 
+0

怎麼樣在a計數爲零的lphabet,就像我在字母B的示例中所顯示的那樣,我還需要獲取這些信息? – cghrmauritius 2014-10-29 07:55:56

0

,只要你想顯示其不存在在列表中,你可能需要一個查找表,以及再與查找表加入的字符你可以做

select 
left(UPPER(firstname),1) as initial , 
count(*) as tot from users 
group by initial ; 

更新。查找表只會有字母

select 
a.alpha, 
coalesce(b.tot,0) as total 
from alphabets a 
left join 
(
    select 
    left(UPPER(firstname),1) as initial , 
    count(*) as tot from users 
    group by initial 
)b 
on b.initial = a.alpha 
; 

OR

select 
a.alpha, 
count(u.firstname) as tot 
from 
alphabets a 
left join users u on a.alpha = left(UPPER(u.firstname),1) 
group by a.alpha 

DEMO

0

希望如此,這將幫助。

SELECT LEFT(firstname,1) as character, COUNT(1) as totalCount 
FROM contacts 
GROUP BY initial ORDER BY firstname; 
0

難的方法也

SELECT 
'A' as letter , 
    count(*) as total FROM totalCount 
    WHERE left(UPPER(firstname),1)='A' 
    UNION 
    SELECT 
    'B' as letter , 
    count(*) as total FROM totalCount 
    WHERE left(UPPER(firstname),1)='B' 
    ..... 
    UNION 
    SELECT 
    'Z' as letter , 
    count(*) as total FROM totalCount 
    WHERE left(UPPER(firstname),1)='Z' 
0

創建另一張桌子

table_letter 
id letter 
1 A 
2 B 
3 C 
... 
26 Z 

SELECT a.letter, COUNT(b.name) as total 
FROM table_letter a 
LEFT JOIN contacts b 
ON a.letter = left(UPPER(b.name),1) 
GROUP BY a.letter 
相關問題