从另一个 table 填充空值
Populate empty values from another table
假设我有两个 SQL tables
员工认可度Table
Employee Id
Reward Date
Coupon
1
1/1/2020
null
1
1/2/2020
null
1
1/3/2020
null
2
2/1/2020
null
2
2/2/2020
null
3
2/2/2020
null
优惠券
Employee Id
Coupon
1
COUPON1
1
COUPON2
1
COUPON3
2
COUPON4
我想做的是给所有员工唯一分配优惠券,例如
- 员工 1 有三张优惠券,因此应该分配给他们
- 员工 2 只有 1 张优惠券,因此应该分配 1 张
- 员工 3 none
所以输出应该是这样的
员工认可Table已更新
Employee Id
Reward Date
Coupon
1
1/1/2020
COUPON1
1
1/2/2020
COUPON2
1
1/3/2020
COUPON3
2
2/1/2020
COUPON4
2
2/2/2020
null
3
2/2/2020
null
此外,table 包含大量记录,其中 table 超过 10 万条记录,所以想知道高性能查询会是什么样子。我考虑过使用横向连接,但速度似乎是问题所在。
下面使用
select * except(pos)
from (
select Employee_Id, Reward_Date,
row_number() over(partition by Employee_Id order by Reward_Date) pos
from recognitions
)
left join (
select Employee_Id, Coupon,
row_number() over(partition by Employee_Id order by Coupon) pos
from coupons
)
using (Employee_Id, pos)
-- order by Employee_Id, Reward_Date
如果应用于您问题中的示例数据 - 输出为
假设我有两个 SQL tables
员工认可度Table
Employee Id | Reward Date | Coupon |
---|---|---|
1 | 1/1/2020 | null |
1 | 1/2/2020 | null |
1 | 1/3/2020 | null |
2 | 2/1/2020 | null |
2 | 2/2/2020 | null |
3 | 2/2/2020 | null |
优惠券
Employee Id | Coupon |
---|---|
1 | COUPON1 |
1 | COUPON2 |
1 | COUPON3 |
2 | COUPON4 |
我想做的是给所有员工唯一分配优惠券,例如
- 员工 1 有三张优惠券,因此应该分配给他们
- 员工 2 只有 1 张优惠券,因此应该分配 1 张
- 员工 3 none
所以输出应该是这样的
员工认可Table已更新
Employee Id | Reward Date | Coupon |
---|---|---|
1 | 1/1/2020 | COUPON1 |
1 | 1/2/2020 | COUPON2 |
1 | 1/3/2020 | COUPON3 |
2 | 2/1/2020 | COUPON4 |
2 | 2/2/2020 | null |
3 | 2/2/2020 | null |
此外,table 包含大量记录,其中 table 超过 10 万条记录,所以想知道高性能查询会是什么样子。我考虑过使用横向连接,但速度似乎是问题所在。
下面使用
select * except(pos)
from (
select Employee_Id, Reward_Date,
row_number() over(partition by Employee_Id order by Reward_Date) pos
from recognitions
)
left join (
select Employee_Id, Coupon,
row_number() over(partition by Employee_Id order by Coupon) pos
from coupons
)
using (Employee_Id, pos)
-- order by Employee_Id, Reward_Date
如果应用于您问题中的示例数据 - 输出为