Search code examples
oracle-databasegroup-byaggregatereduction

Reduction columns are not working for group by expression in oracle


I tried to concat two columns and using group by expression, but it is not work. how can I grouped multiple columns in oracle. first_name and last_name are reduction data.

SELECT employee_id,
  employee_name,
  employee_unique
FROM
  (SELECT a.id AS employee_id,
    (a.first_name
    || a.last_name) AS employee_name,
    b.employee_unique
  FROM A a
  INNER JOIN b
  ON a.id=b.employee_id
  GROUP BY a.id,
    b.employee_unique,
    (a.first_name
    || a.last_name)
  );

Solution

  • What does "not work" mean? It works for me (though, as I don't have your tables, I used Scott's EMP and DEPT, but everything else is more or less the same). If it isn't correct, you should explain what is wrong with it. If you want us to work with your data, please, provide CREATE TABLE and INSERT INTO sample data.

    SQL> select employee_id,
      2         employee_name,
      3         employee_unique
      4  from
      5    (select a.empno          as employee_id,
      6            a.ename || a.job as employee_name,
      7            b.dname          as employee_unique
      8    from emp a
      9    inner join dept b
     10       on a.deptno=b.deptno
     11    group by a.empno,
     12             b.dname,
     13             a.ename || a.job
     14    );
    
    EMPLOYEE_ID EMPLOYEE_NAME       EMPLOYEE_UNIQU
    ----------- ------------------- --------------
           7654 MARTINSALESMAN      SALES
           7876 ADAMSCLERK          RESEARCH
           7566 JONESMANAGER        RESEARCH
           7698 BLAKEMANAGER        SALES
           7844 TURNERSALESMAN      SALES
           7369 SMITHCLERK          RESEARCH
           7788 SCOTTANALYST        RESEARCH
           7900 JAMESCLERK          SALES
           7902 FORDANALYST         RESEARCH
           7782 CLARKMANAGER        ACCOUNTING
           7934 MILLERCLERK         ACCOUNTING
           7499 ALLENSALESMAN       SALES
           7521 WARDSALESMAN        SALES
           7839 KINGPRESIDENT       ACCOUNTING
    
    14 rows selected.
    
    SQL>
    

    Though, as there's nothing really to be grouped (no aggregation here), you could have used distinct (without group by clause) and get the same result:

    select employee_id,
           employee_name,
           employee_unique
    from
      (select distinct
              a.empno          as employee_id,
              a.ename || a.job as employee_name,
              b.dname          as employee_unique
      from emp a
      inner join dept b
         on a.deptno=b.deptno
      );