如何根据日期条件在SQL中赋值

问题描述 投票:0回答:0

我有一个表格,我需要在其中更新订单的公差值。公差值基于零售商。可以有多个适用于给定时间范围的公差值。我需要能够更新在容差时间范围内创建的订单的容差值。

例如我有以下公差细节:

客户编号 客户名称 early_tolerance late_tolerance 开始日期 结束日期
1 ABC 15 1 1/1/2001 2023/4/17
1 ABC 2 1 2023/4/18
5 EEE 6 2 2/18/2020
9 JD 5 5 6/18/2021

我加入的表2:

订单号 order_create_date 客户编号 客户名称
50 2020-09-18 00:00:00.000 1 ABC
21 2021-10-30 00:00:00.000 1 ABC
33 2023-03-23 00:00:00.000 1 ABC
26 2022-09-12 00:00:00.000 1 ABC
15 2023-04-18 00:00:00.000 1 ABC
40 2023-04-20 00:00:00.000 1 ABC
130 2023-04-20 00:00:00.000 5 EEE
407 2023-04-02 00:00:00.000 9 JD
409 2022-01-20 00:00:00.000 9 JD
320 2020-05-28 00:00:00.000 5 EEE

需要以下输出:

订单号 order_create_date 客户编号 客户名称 early_tolerance late_tolerance
50 2020-09-18 00:00:00.000 1 ABC 15 1
21 2021-10-30 00:00:00.000 1 ABC 15 1
33 2023-03-23 00:00:00.000 1 ABC 15 1
26 2022-09-12 00:00:00.000 1 ABC 15 1
15 2023-04-18 00:00:00.000 1 ABC 2 1
40 2023-04-20 00:00:00.000 1 ABC 2 1
130 2023-04-20 00:00:00.000 5 EEE 6 2
407 2023-04-02 00:00:00.000 9 JD 5 5
409 2022-01-20 00:00:00.000 9 JD 5 5
320 2020-05-28 00:00:00.000 5 EEE 6 2

公差值根据 order_create_date 落在公差表的 start_date 和 end_date 范围内。因此,对于给定的示例,早于或等于 4/17/2023 的所有订单都应具有旧的公差值 15, 1,而之后的订单将具有 2,1。在某些情况下,我们可以有超过 2 个不同的公差条目。

  select order_no, order_create_date, cust_no, cust_name, case when order_create_date 
  between start_date and end_date then early_tolerance end as early_tolerance, case 
  when order_create_date 
  between start_date and end_date then late_tolerance end as late_tolerance from 
  table1 left join table2 on table1.cust_no = table2.cust_no

我认为这行不通,因为我还需要考虑 NULL 结束日期。请建议如何最好地解决这个问题。谢谢。

sql presto
© www.soinside.com 2019 - 2024. All rights reserved.