有人可以帮助我获得以下逻辑的结果。我有一个表,有以下列。
TYPE SRC_CURR TAR_CURR EX_RATE EX_RATE_START_DATE
M GBP USD 1.36687 2/1/2021
M GBP USD 1.33636 1/1/2021
M GBP USD 1.32837 12/1/2020
M GBP USD 1.30242 11/1/2020
M GBP USD 1.27421 10/1/2020
M GBP USD 1.31527 9/1/2020
ZEU GBP USD 1.3654 1/20/2021
ZEU GBP USD 1.363 1/19/2021
ZEU GBP USD 1.3587 1/18/2021
ZEU GBP USD 1.359 1/15/2021
ZEU GBP USD 1.3689 1/14/2021
ZEU GBP USD 1.3639 1/13/2021
ZEU GBP USD 1.3664 1/12/2021
ZEU GBP USD 1.3518 1/11/2021
ZEU GBP USD 1.3568 1/8/2021
所以我需要从上面的值形成一个新的列EX_RATE_END_DATE如下所示。理想情况下,需要将最新开始日期的EX_RATE_END_DATE默认设置为最大99999-12-31,而对于其余记录,它应该是以前的最大开始日期-1。
请在要求的输出下面找到
TYPE SRC_CURR TAR_CURR EX_RATE EX_RATE_START_DATE EX_RATE_END_DATE
M GBP USD 1.36687 2/1/2021 12/31/9999
M GBP USD 1.33636 1/1/2021 1/31/2021
M GBP USD 1.32837 12/1/2020 12/31/2020
M GBP USD 1.30242 11/1/2020 11/30/2020
M GBP USD 1.27421 10/1/2020 10/31/2020
M GBP USD 1.31527 9/1/2020 9/30/2020
ZEU GBP USD 1.3654 1/20/2021 12/31/9999
ZEU GBP USD 1.363 1/19/2021 1/19/2021
ZEU GBP USD 1.3587 1/18/2021 1/18/2021
ZEU GBP USD 1.359 1/15/2021 1/17/2021
ZEU GBP USD 1.3689 1/14/2021 1/14/2021
ZEU GBP USD 1.3639 1/13/2021 1/13/2021
ZEU GBP USD 1.3664 1/12/2021 1/12/2021
ZEU GBP USD 1.3518 1/11/2021 1/11/2021
ZEU GBP USD 1.3568 1/8/2021 1/10/2021
如果有人帮助我在snowflake中以任何可能的方式获得所需的结果集,那将是伟大的。
请检查以下查询:select TYPE, SRC_CURR, TAR_CURR, EX_RATE, EX_RATE_START_DATE, CASE WHEN DATE_VALUE = 1 THEN '9999-12-31' ELSE LAST_DAY("EX_RATE_START_DATE", 'MONTH') END AS "LAST DAY OF YEAR" from ( SELECT TYPE, SRC_CURR, TAR_CURR, EX_RATE, EX_RATE_START_DATE, row_number() over(partition by type order by EX_RATE_START_DATE desc) as date_value FROM SOF_TEST1) a;
我发现了下面的逻辑来获得所需的结果。如果可以用更好的/其他的方式实现,请评论。
select
TYPE,
SRC_CURR,
TAR_CURR,
EX_RATE,
EX_RATE_START_DATE ,
lag(EX_RATE_START_DATE) over ( PARTITION BY TYPE,SRC_CURR,TAR_CURR order by EX_RATE_START_DATE desc) as END_TEMP,
case when END_TEMP is NULL then '9999-12-31' else END_TEMP end as EX_RATE_END_DATE
from schema.target_table
order by TYPE,SRC_CURR,EX_RATE_START_DATE desc ;