sql - 如何在交叉连接中插入空值?
问题描述
我这里有问题。我有 2 个表,它们由“id.x”列链接 一个表有给定月份的周数,例如,对于 1 月,该表有 5 行,每个月的每个星期。另一张表代表员工在给定一周内的工作量。
我想加入这两个表,但我想以某种方式向我展示一个员工在给定一周内的努力,所以在这种情况下,每个员工 5 个注册表,即使他在某个周内没有注册努力,在这种情况下,我们将努力设置为空。
如果可能的话,我会给你一个我正在寻找的东西的代表。
Table 1:
id week month year id.x
1 1 1 2019 7819
2 2 1 2019 7819
3 3 1 2019 7819
4 4 1 2019 7819
5 5 1 2019 7819
Table 2:
employee_id effort id.x week
63 100 7819 3
我想要的结果:
employee week effort id.x
63 1 null 7819
63 2 null 7819
63 3 100 7819
63 4 null 7819
63 5 null 7819
有可能达到这个结果吗?
我目前正在尝试这个查询:
select t2.employee, t1.week from
table_2 t2
cross join
table_1 tt
order by t2.employee, t1.week;
编辑:
如果我想对给定一周的值求和?例如:
表 2 现在有:
employee_id effort id.x week
63 60 7819 3
63 40 7819 3
但我想要同样的答案:
我想要的结果:
employee week effort id.x
63 1 null 7819
63 2 null 7819
63 3 100 7819
63 4 null 7819
63 5 null 7819
解决方案
使用PARTITION OUTER JOIN
:
甲骨文设置:
CREATE TABLE Table1 ( id, week, month, year, id_x ) AS
SELECT 1, 1, 1, 2019, 7819 FROM DUAL UNION ALL
SELECT 2, 2, 1, 2019, 7819 FROM DUAL UNION ALL
SELECT 3, 3, 1, 2019, 7819 FROM DUAL UNION ALL
SELECT 4, 4, 1, 2019, 7819 FROM DUAL UNION ALL
SELECT 5, 5, 1, 2019, 7819 FROM DUAL;
CREATE TABLE Table2 ( employee_id, effort, id_x, week ) AS
SELECT 63, 100, 7819, 3 FROM DUAL;
查询:
SELECT t2.employee_id,
t1.week,
t2.effort,
t1.id_x
FROM Table2 t2
PARTITION BY ( employee_id )
RIGHT OUTER JOIN table1 t1
ON (
t1.week = t2.week
AND t1.id_x = t2.id_x
)
输出:
员工 ID | 周 | 努力 | ID_X ----------: | ---: | -----: | ---: 63 | 1 | 空| 7819 63 | 2 | 空| 7819 63 | 3 | 100 | 7819 63 | 4 | 空| 7819 63 | 5 | 空| 7819
db<>在这里摆弄
推荐阅读
- python - ImportError:无法导入 Django。在虚拟环境中工作
- matplotlib - 以国家为中心的 geopandas 地图
- sql - 如何为每个用户获取行作为具有计数的列
- java - Android Studio 和侦听器适配器
- javascript - 如何保持组件在后台运行以做出反应?
- dart - 一些系统将越南语组合重音编码为单个 utf-8 字符
- javascript - 玩笑配置错误:“未找到预设 @shelf/jest-mongodb。”
- vba - VBA - 将日语密钥添加到 DICT 时出现运行时错误 457
- amazon-web-services - AWS Elastic Beanstalk 外部 DNS 未正确路由
- r - 如何在R中选择重复多年的特定日期范围?