简体   繁体   中英

SAP HANA: Not able to generate the required output with COUNT and CASE function IN SQL

This is a scenario with single user assigned to multiple branches (1 to many)

I want to group users on the basis of office assigned to that user. Based on the office assigned I want to create 2 columns in the select statement:

  1. The count of offices assigned to this user

  2. The name of the offices assigned to this user

This is the output I get with SQL (see below):

USER_LABEL          NUMBER_OFFICE_ASSIGNED   BRANCH_ASSIGNED      
-------------------------------------------------------------
FARAG                       1                  HQ
FARAG                       1                  SCM
FARAG                       1                  TCD
FARAG                       1                  TCM

This is the output that I require:

USER_LABEL          NUMBER_OFFICE_ASSIGNED   BRANCH_ASSIGNED      
-------------------------------------------------------------
FARAG                       4                  HQ,SCM,TCD,TCM

How to do it?

The SQL code is as follows:

SELECT us.USER_LABEL ,
count(od.office_id) AS "NUMBER_OFFICE_ASSIGNED",
CASE 
   WHEN od.OFFICE_ID=4 THEN 'HQ' 
   WHEN od.OFFICE_ID=5 THEN 'TCM'
   WHEN od.OFFICE_ID=6 THEN 'TCD'
   WHEN od.OFFICE_ID=7 THEN 'SCM'
   WHEN od.OFFICE_ID=8 THEN 'SSAAC' 
ELSE 'No branch assigned. Check with Admin'
END AS "BRANCH_ASSIGNED"    
FROM VIEW_USER_SETUP us
INNER JOIN USERS_DEPARTMENTS ud 
on(us.USER_ID=ud.USER_ID)
INNER JOIN DEPARTMENT_SETUP ds
on(ud.DEPARTMENT_ID=ds.DEPARTMENT_ID)
INNER JOIN DEPARTMENT_OFFICE do 
on(ds.DEPARTMENT_ID=do.DEPARTMENT_ID)
INNER JOIN OFFICE_DETAILS od 
on(do.OFFICE_ID=od.OFFICE_ID)
WHERE
   ds.ACTIVE_STATUS ='Y'
AND 
   do.ACTIVE_STATUS='Y'
AND 
   od.ACTIVE_STATUS='Y'
AND 
   us.ACTIVE_STATUS ='Y'
AND 
   us.USER_TYPE ='D'
AND 
   us.USER_LABEL NOT IN('Emergency Room','General Doctor','General Doctor Oph')
GROUP BY 
    us.USER_LABEL, 
    od.OFFICE_ID
ORDER BY 
    us.USER_LABEL ASC;

First, you should remove od.OFFICE_ID from the GROUP BY clause since ultimately, you do not want to group by OFFICE_ID . This change requires you to apply an aggregation to your CASE projection since it uses OFFICE_ID . The correct aggregation method based on your desired output is function STRING_AGG .

The resulting statement looks something like

SELECT 
   us.USER_LABEL ,
   count(od.office_id) AS "NUMBER_OFFICE_ASSIGNED",
   STRING_AGG(CASE .... END, ',') AS "BRANCH_ASSIGNED"    
FROM ...
WHERE ...
GROUP BY 
    us.USER_LABEL
ORDER BY 
    us.USER_LABEL ASC;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM