Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

sql - group by first character

I have a problem with a query in Oracle SQL.

I have a first_name column in an employees table. I want to group my records according to the first character in first_name.

For example, I have 26 records, one with name = 'Alice', one with name = 'Bob', and so on down the alphabet for each name's first character. After the query, there should be 26 groups with one employee each.

I tried the following, but it's not working:

SELECT employee_id, (SUBSTR(first_name,1,1)) AS alpha FROM employees
GROUP BY alpha;

name_which_starts_from       employees  
A                            10  
B                            2  
C                            4  
D                            9  
E                            3  
G                            3  
H                            3  
I                            2  
J                            16  
K                            7  
L                            6  
M                            6  
N                            4  
O                            1  
P                            6  
R                            3  
S                            13  
T                            4  
V                            2  
W                            3  
question from:https://stackoverflow.com/questions/666525/group-by-first-character

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your query is wrong, since you would need to perform some aggregation function on EMPLOYEE_ID if you want that to work.

Like:

select substr(first_name,1,1) as alpha, count(employee_id)
  from employees
 group by substr(first_name,1,1)

What exactly you are trying to accomplish?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...