0

请点击此处查看示例表格和说明。

根据附加图像,我有三个表“PROJECTS”、“PROJECTMANAGER”和“MANAGERS”。

我需要一个查询,它可以列出由“产品”类型管理器管理的项目,这些管理器与项目状态分组。如果 STATUS=2 则显示为 Completed Projects 或 In Progress Projects。

结果表应如附图所示。期望的结果:http ://www.dbasupport.com/forums/attachment.php?attachmentid=588&d=1336691473

我需要的查询应该是通用的,以便可以在任何数据库(MySQL/Oracle/MSSQL/DB2)中使用

请帮忙。

顺便说一句,这不是作业......!!!!我使用了示例表。

我尝试过 case when 语句,但不知道如何加入并同时使用 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          |
4

2 回答 2

2

由于我看不到您想要的最终结果(没有发布图片),因此您可以执行以下操作:

select p.project_id
  , p.project_name
  , m.manager_name
  , case when p.status = 2 then 'completed' else 'in progress' end as projectstatus
from projects p
left join projectmanager pm
  on p.project_id = pm.project_id
left join managers m
  on pm.manager_id = m.manager_id
WHERE m.type = 'Product'

SQL Fiddle with Demo

我认为您想要以下内容:

SELECT *
  FROM
  (
    select m.manager_id
      , m.manager_name
      , status
      , case when status = '2' then 'Completed' else 'in progress' end as pstatus
    from projects p
    left join projectmanager pm
      on p.project_id = pm.project_id
    left join managers m
      on pm.manager_id = m.manager_id
    WHERE m.type = 'Product'
  ) x
  pivot
  (
    count(status)
    for pstatus in ([completed], [in progress])
  ) p

演示

于 2012-05-10T23:24:07.790 回答
0

您需要使用 INNER JOIN 将表连接在一起(使用 project_id 的项目到 Projectmanager,使用 manager_id 的 projectmanager 到经理)。

然后将它们与 GROUP BY 组合在一起

还阅读了 T-SQL CASE 语句。您需要它(或 IF)将 STATUS 字段转换为“已完成”或“未完成”。

于 2012-05-10T23:22:01.247 回答