group-byleft-joincase-whenhaving-clause

Case When + Join + Group By + Having SQL Query


Please click here for sample tables and description.

I have three tables ‘PROJECTS’, 'PROJECTMANAGER' and ‘MANAGERS' as per attached images.

I need a query which can list PROJECTS managed by “PRODUCT” type managers grouped with PROJECT STATUS. If STATUS=2 then show as Completed Projects or else In Progress Projects.

Resulted table should look like as shown in attached image. Desired Result: http://www.dbasupport.com/forums/attachment.php?attachmentid=588&d=1336691473

The query, I need should be generic so that it can be used in any database (MySQL/Oracle/MSSQL/DB2)

Please Help.

BTW, This is not the homework...!!!! I used sample tables.

I have tried with case when statements but don't know how to join and at the same time use group by.

CREATE TABLE PROJECTS 
(       
    PROJECT_ID  varchar(20), 
    PROJECT_NAME  varchar(30),
    STATUS int
);

CREATE TABLE PROJECTMANAGER
(
    PROJECT_ID  varchar(20), 
    MANAGER_ID varchar(20)
);

CREATE TABLE MANAGERS
(           
    MANAGER_ID  varchar(20), 
    MANAGER_NAME  varchar(20), 
    TYPE varchar(20)
);


INSERT INTO PROJECTS (PROJECT_ID, PROJECT_NAME, STATUS) VALUES
    ('project_001', 'Project 001', 0),
    ('project_002', 'Project 002', 1),
    ('project_003', 'Project 003', 2),
    ('project_004', 'Project 004', 0),
    ('project_005', 'Project 005', 2),
    ('project_006', 'Project 006', 0),
    ('project_007', 'Project 007', 1);


INSERT INTO PROJECTMANAGER (PROJECT_ID , MANAGER_ID) VALUES
    ('project_001', 'mgr_001'),
    ('project_002', 'mgr_001'),
    ('project_001', 'mgr_002'),
    ('project_002', 'mgr_003'),
    ('project_001', 'mgr_003'),
    ('project_005', 'mgr_001'),
    ('project_004', 'mgr_002');

INSERT INTO MANAGERS (MANAGER_ID, MANAGER_NAME, TYPE) VALUES
    ('mgr_001', 'Manager 001', 'PRODUCT'),
    ('mgr_002', 'Manager 002', 'HR'),
    ('mgr_003', 'Manager 003', 'PRODUCT'),
    ('mgr_004', 'Manager 004', 'FINANCE'),
    ('mgr_005', 'Manager 005', 'PRODUCT');



Resulted Table:

MANAGER_ID  | MANAGER _NAME | COMPLETED_PROJECTS |  IN_PROGRESS_PROJECTS |
 mgr_001    | Manager 001   |        1       |            2          |
 mgr_003    | Manager 003   |        0       |            1          |
 mgr_005    | Manager 005   |        0       |            0          |

Solution

  • Try something like this:

    SELECT
      m.manager_id,
      m.manager_name,
      SUM(CASE WHEN p.status = 2 THEN 1 ELSE 0 END) as completed,
      SUM(CASE WHEN p.status != 2 THEN 1 ELSE 0 END) as in_progress
    FROM managers m
    LEFT JOIN projectmanager pm ON (m.manager_id = pm.manager_id)
    LEFT JOIN projects p ON (p.project_id = pm.project_id)
    WHERE m.type = 'product'
    GROUP BY m.manager_id