Select the sum of occurances of first alphabetical character

和自甴很熟 提交于 2019-12-25 14:14:29

问题


Hi what i need to do is create a select statement which outputs the sum of the first character in a field within the table so the output would look something like

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

The table is called contacts, in the above there was 12 occurrences of people whose names begin with the letter A

I hope i have explained this correctly


回答1:


Let's understand this with EMP table example.

SQL> with
  2      letters
  3      as
  4      (select chr( ascii('A')+level-1 ) letter
  5         from dual
  6      connect by level <= 26
  7      )
  8  SELECT substr(ename, 1, 1) AS init_name,
  9  count(*) cnt
 10  FROM emp
 11  WHERE substr(ename, 1, 1) IN (SELECT letter from letters)
 12  GROUP BY substr(ename, 1, 1)
 13  UNION
 14  SELECT l.letter AS init_name,
 15  0 cnt
 16  FROM letters l
 17  WHERE l.letter NOT IN (SELECT substr(ename, 1, 1) FROM emp)
 18  ORDER BY init_name
 19  /

I        CNT
- ----------
A          2
B          1
C          1
D          0
E          0
F          1
G          0
H          0
I          0
J          2
K          1
L          0
M          2
N          0
O          0
P          0
Q          0
R          0
S          2
T          1
U          0
V          0
W          1
X          0
Y          0
Z          0

26 rows selected.

SQL>

So, it gives the count of each letter of first name, and for the other letters which does not exist in the first name, the count is 0.




回答2:


Generate the 26 letters using connect then left join to the first letter of the name and count them:

select letter, count(name) count
from (select chr(ascii('A')+level-1) letter from dual connect by level < 27) l
left join emp on substr(name, 1, 1) = letter
group by letter order by 1

See SQLFiddle

Attribution: My technique of generating letters uses elements of Lalit's answer.



来源:https://stackoverflow.com/questions/26623733/select-the-sum-of-occurances-of-first-alphabetical-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!