Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

transform more row in one row oracle sql

How convert more row in one oracle sql?

Example:

Create table EMP(
        emp_id number,
        emp number,
        code number,
        date_start date,
        date_end date
    )
    
    
    Insert into EMP (emp_id,emp,code,date_start,date_end) VALUES (1,100,1,sysdate,sysdate + 1/24);
    Insert into EMP (emp_id,emp,code,date_start,date_end) VALUES (2,100,1,sysdate,sysdate + 1/24);
    Insert into EMP (emp_id,emp,code,date_start,date_end) VALUES (3,100,2,sysdate,sysdate + 1/24);
    Insert into EMP (emp_id,emp,code,date_start,date_end) VALUES (4,100,1,sysdate,sysdate + 1/24);

How get resault as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EMP    CODE_1       CODE_2
----------------------------------
100    3 (hours)    1 (hours)

3 hours is date_end – date_start

>Solution :

You can use PIVOT:

SELECT *
FROM   (SELECT emp, code, 24 * (date_end - date_start) AS hours FROM emp)
PIVOT (
  SUM(hours) FOR code IN (
    1 AS code_1,
    2 AS code_2
  )
);

or conditional aggregation:

SELECT emp,
       SUM(CASE code WHEN 1 THEN 24 * (date_end - date_start) END) AS code_1,
       SUM(CASE code WHEN 2 THEN 24 * (date_end - date_start) END) AS code_2
FROM   emp
GROUP BY emp;

Which, for the sample data, both output:

EMP CODE_1 CODE_2
100 3 1

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading