Search code examples
sqloracle-databasegroup-by

How to List aggregate values using Group By in oracle


I have a query which get all the users with reporting managers. I would like to group the user ids as a list by reporting manager email id.

SELECT q.USER_ID, q.REPORTS_TO, e.EMAIL
  FROM (SELECT a.USER_ID, a.REPORTS_TO, a.EMAIL
          FROM PortalX.PTX_USERS a
               LEFT OUTER JOIN PortalX.PTX_LDAP_USERS b
                  ON a.USER_ID = b.OWN_ID
         WHERE b.OWN_ID IS NULL) q
       INNER JOIN PortalX.PTX_USERS e ON q.REPORTS_TO = e.USER_ID;

I am not very familiar with writing oracle queries. Any help is appreciated.

Edit:

with the help of @Barbaros her is the final query which aggregates the users as a list of comma separated values.

SELECT a.REPORTS_TO, a.EMAIL, 
       LISTAGG(a.USER_ID,',') WITHIN GROUP (ORDER BY a.USER_ID) as USERS
  FROM PortalX.PTX_USERS a
  LEFT JOIN PortalX.PTX_LDAP_USERS b
    ON a.USER_ID = b.OWN_ID
   AND a.REPORTS_TO = a.USER_ID
 WHERE b.OWN_ID IS NULL
 GROUP BY a.REPORTS_TO, a.EMAIL;

Solution

  • You can use such a query

    SELECT pu.reports_to,
           pu.email,
           LISTAGG(pu.user_id) WITHIN GROUP (ORDER BY pu.user_id) AS users
      FROM PortalX.ptx_users pu
      LEFT JOIN PortalX.ptx_ldap_users plu
        ON pu.user_id = plu.own_id
       AND pu.reports_to = pu.user_id
     WHERE plu.own_id IS NULL
     GROUP BY pu.reports_to, pu.email;
    

    containing LISTAGG() function