group by first character

為{幸葍}努か 提交于 2019-11-27 13:28:27

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?

You'll need to group by everything that is not an aggregate function, so you can't have employee_id in the SELECT projection. You also need to group by just the first character of the first_name. Something like this should work:

SELECT  SUBSTR(first_name, 1, 1) AS alpha, COUNT(*) AS employee_count
FROM    employees
GROUP   BY SUBSTR(first_name, 1, 1);

That would group by the first letter of the first name, and show the number of employees that fall into that group.

It almost sounds like you want 26 records returned with A, B, C as the first column and then a second column containing all the employee IDs in a delimited list. If so see question 468990 and/or this Ask Tom link. Something like (untested)

SELECT SUBSTR(first_name,1,1), TO_STRING( CAST( COLLECT( employee_id ) AS ntt_varchar2 ) ) AS empIDs
FROM   employees
GROUP  BY
SUBSTR(first_name,1,1);

When you are grouping, all of the columns that appear in your select list that are not aggregated have to also appear in the "group by" clause (employee_id does not).

Could you clarify what it is you are trying to do?

In Rails/postgres that might look something like this

group_clause = 'UPPER(LEFT(name, 1))'
Division.group(group_clause).order(group_clause).pluck(group_clause, 'COUNT(id)')
user3418801

I have similar issue and solved it this with statement:

select SUBSTR(word, 1, 1) as S, count(word) FROM table_words group by S order by S ASC

I think i know what you are trying to do...

You should create a small reference table with a column 'letter' (letter, sort_order)

You should your query as

select l.letter, count(e.id) as employees from letter l left outer join employee e on l.letter = substr(e.first_name, 1,1)

the other answer posted will give you unexpected results when there are no employees with a specific letter in their name...

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