我需要做的是创建一个select语句,输出表中字段中第一个字符的总和,使输出看起来像
A,12
B,0
C,20
D,14
E,0
ect...
该表被称为联系人,在上面有12个人的名字以字母A开头,并且出现了0个字母B.
我希望我已经正确解释了
答案 0 :(得分:0)
试试这个:
select substr(name, 1,1), count(*) from contacts group by substr(name, 1,1)
答案 1 :(得分:0)
你可以这样做
select
left(UPPER(firstname),1) as initial ,
count(*) as tot from users
group by initial ;
UPDATE因为你想要显示列表中不存在的字符,你可能还需要一个查找表,然后加入查找表。查找表只有字母
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 强>
答案 2 :(得分:0)
希望这会有所帮助。
SELECT LEFT(firstname,1) as character, COUNT(1) as totalCount
FROM contacts
GROUP BY initial ORDER BY firstname;
答案 3 :(得分: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
答案 4 :(得分: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'
答案 5 :(得分: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