根据其他列创建列但有条件
Create column based on other column but with conditions
我是 SQL 的新手,我只是无法为以下内容制定方法:
我有这个 table 和代码的开始日期
Row Code Start Date Product
1 A1 2020-01-01 X
2 A1 2020-05-15 Y
3 A2 2020-02-02 X
4 A3 2020-01-31 Z
5 A3 2020-02-15 Y
6 A3 2020-12-31 X
最终我需要能够查询另一个 table 并找出代码在特定日期是什么产品,因此 2020-01-10 的代码 A1 = X,但今天的代码 A1 是= Y
我想我可以弄清楚如何在 where 子句中使用 between 语句,但我不知道如何更改 table 以具有结束日期,因此它看起来像这样:
Row Code Start_Date Product End_Date
1 A1 2020-01-01 X 2020-05-14
2 A1 2020-05-15 Y NULL
3 A2 2020-02-02 X NULL
4 A3 2020-01-31 Z 2020-02-14
5 A3 2020-02-15 Y 2020-12-30
6 A3 2020-12-31 X NULL
请注意数据库没有 End_Date 字段
我想你想要 lead()
:
select t.*,
dateadd(day, -1,
lead(start_date) over (partition by code order by start_date)
) as end_date
from t;
注意:我建议不要将结束日期减去一天,这样结束日期是不包括在内的。这使得结束日期与下一个开始日期相同,我发现这样更容易确保数据中没有间隙或重叠。
我是 SQL 的新手,我只是无法为以下内容制定方法:
我有这个 table 和代码的开始日期
Row Code Start Date Product
1 A1 2020-01-01 X
2 A1 2020-05-15 Y
3 A2 2020-02-02 X
4 A3 2020-01-31 Z
5 A3 2020-02-15 Y
6 A3 2020-12-31 X
最终我需要能够查询另一个 table 并找出代码在特定日期是什么产品,因此 2020-01-10 的代码 A1 = X,但今天的代码 A1 是= Y
我想我可以弄清楚如何在 where 子句中使用 between 语句,但我不知道如何更改 table 以具有结束日期,因此它看起来像这样:
Row Code Start_Date Product End_Date
1 A1 2020-01-01 X 2020-05-14
2 A1 2020-05-15 Y NULL
3 A2 2020-02-02 X NULL
4 A3 2020-01-31 Z 2020-02-14
5 A3 2020-02-15 Y 2020-12-30
6 A3 2020-12-31 X NULL
请注意数据库没有 End_Date 字段
我想你想要 lead()
:
select t.*,
dateadd(day, -1,
lead(start_date) over (partition by code order by start_date)
) as end_date
from t;
注意:我建议不要将结束日期减去一天,这样结束日期是不包括在内的。这使得结束日期与下一个开始日期相同,我发现这样更容易确保数据中没有间隙或重叠。