我在Sql Server中有3个表。以下是表的结构。
employee表将包含员工列表。项目表将具有项目列表。映射表将在员工与项目之间以及每个星期的小时数之间进行映射。映射表将没有针对所有员工和项目的映射。 我需要加入3个表,并在一个星期内获得一个特殊项目的所有员工的结果。如果某个特殊员工本周末没有工作时间,则应提供员工详细信息,但工作时间应为0。
我有以下查询,但它仅显示映射表中具有weekEnding值的员工。
SELECT RT.EMP_ID,RT.EMP_NAME, RT.EMP_EMAIL_ID, RPM.WEEK_ENDING, RPM.RSC_HOURS_LOGGED
FROM vl.rsrc_prjct_hrs_mapping RPM right outer Join vl.resource RT ON RT.EMP_ID = RPM.EMP_ID
JOIN
vl.project PT ON PT.PROJECT_ID=RPM.PROJECT_ID WHERE PT.PROJECT_IRM='TMPT-4854' AND
PT.PROJECT_DESC='33801-Urgent Care EnhancementEPDS V2' AND
RPM.WEEK_ENDING BETWEEN '2018-07-07' AND '2018-08-07';
但是我希望所有的员工都可以参加,但是应该到结局的一周,小时数应该为0。
我也尝试使用以下查询:
select RT.EMP_ID,RT.EMP_NAME, RT.EMP_EMAIL_ID,tt.week_ending,tt.RSC_HOURS_LOGGED from vl.resource RT left outer join (select RPM.EMP_ID,RPM.WEEK_ENDING, RPM.RSC_HOURS_LOGGED from vl.rsrc_prjct_hrs_mapping RPM join vl.project PT ON PT.PROJECT_ID=RPM.PROJECT_ID WHERE PT.PROJECT_IRM='TMPT-4854' AND PT.PROJECT_DESC='33801-Urgent Care EnhancementEPDS V2' AND RPM.WEEK_ENDING BETWEEN '2018-07-07' AND '2018-07-07') tt on RT.EMP_ID = tt.EMP_ID;
但这给了employee表中的所有雇员,但是我只想要特定项目的雇员。
答案 0 :(得分:0)
RIGHT OUTER JOIN
,其中JOIN
隐式转换为INNER JOIN
,因此右外连接在这里没有用。更改联接的顺序或同时进行外部联接
此外,您需要将RPM.WEEK_ENDING BETWEEN '2018-07-07' AND '2018-08-07'
移至ON
的{{1}}子句
Right outer join
答案 1 :(得分:0)
我不建议使用right join
。这只是令人困惑。使用let join
-将所有行保留在第一个表中,并将匹配的行保留在后续表中。
因此,如果要保留所有员工,则从该表开始:
SELECT RT.EMP_ID, RT.EMP_NAME, RT.EMP_EMAIL_ID, RPM.WEEK_ENDING, RPM.RSC_HOURS_LOGGED
FROM vl.resource RT LEFT JOIN
vl.rsrc_prjct_hrs_mapping RPM
ON RT.EMP_ID = RPM.EMP_ID AND
RPM.WEEK_ENDING BETWEEN '2018-07-07' AND '2018-08-07' LEFT JOIN
vl.project PT
ON PT.PROJECT_ID = RPM.PROJECT_ID AND
PT.PROJECT_IRM = 'TMPT-4854' AND
PT.PROJECT_DESC = '33801-Urgent Care EnhancementEPDS V2' ;
对项目的过滤进入ON
子句。
如果只想让曾经 参加过该项目的人,则需要进行其他过滤。我认为这将满足您的要求:
SELECT RT.EMP_ID, RT.EMP_NAME, RT.EMP_EMAIL_ID, RPM.WEEK_ENDING, RPM.RSC_HOURS_LOGGED
FROM vl.resource RT LEFT JOIN
vl.rsrc_prjct_hrs_mapping RPM
ON RT.EMP_ID = RPM.EMP_ID AND
RPM.WEEK_ENDING BETWEEN '2018-07-07' AND '2018-08-07' LEFT JOIN
vl.project PT
ON PT.PROJECT_ID = RPM.PROJECT_ID AND
PT.PROJECT_IRM = 'TMPT-4854' AND
PT.PROJECT_DESC = '33801-Urgent Care EnhancementEPDS V2'
WHERE EXISTS (SELECT 1
FROM vl.rsrc_prjct_hrs_mapping RPM2 JOIN
vl.project PT2
ON PT2.PROJECT_ID = RPM2.PROJECT_ID AND
PT2.PROJECT_IRM = 'TMPT-4854' AND
PT2.PROJECT_DESC = '33801-Urgent Care EnhancementEPDS V2'
WHERE RPM2.EMP_ID = RF.EMP_ID
);