group by first character

前端 未结 7 1663
天涯浪人
天涯浪人 2020-12-03 04:16

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

相关标签:
7条回答
  • 2020-12-03 04:56

    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?

    0 讨论(0)
  • 2020-12-03 05:01

    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?

    0 讨论(0)
  • 2020-12-03 05:06

    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);
    
    0 讨论(0)
  • 2020-12-03 05:10

    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)')
    
    0 讨论(0)
  • 2020-12-03 05:11

    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

    output

    0 讨论(0)
  • 2020-12-03 05:14

    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.

    0 讨论(0)
提交回复
热议问题