簡體   English   中英

雪花 SQL 案例聲明與 select 並加入

[英]Snowflake SQL case statement with select and joins

我想做的是,當沒有連接來獲取費用時,我想使用 fees_calc 字段中的費用值,該費用值來自 tablea 中找到的最后一個費用值/3。 例如,如果 tableb 中的月份是 2022-10-01 並且 tablea 中沒有可用的季度,則返回到 tablea 並獲取 2022-10-01 之前的最新記錄的最大日期,即 2022-09-30 end_date。 我嘗試查詢,但在 Snowflake 中收到錯誤,指示無法評估不受支持的子查詢類型。

create or replace table tablea (
key varchar(500),
fees varchar(500),
start_date date,
end_date date
)

create or replace table tableb (
key varchar(500),
asofdate date
)


insert into tablea values ('123','100','2022-07-01','2022-09-30'),('345','200','2022-07-01','2022-09-30'),('123','60','2022-04-01','2022-06-30'),('345','60','2022-04-01','2022-06-30')

insert into tableb values ('123','2022-08-01'),('123','2022-09-01'),('123','2022-10-01'),('345','2022-09-01')

select b.key,b.asofdate,
a.fees,a.start_date,a.end_date,
case when a.fees is null then xxx else fees/3 end as fees_calc 
from tableb b 
left join tablea a on b.key = a.key 
and b.asofdate between a.start_date and a.end_date

在此處輸入圖像描述

您可以創建 CTE 以確保首先連接表,然后計算費用。 您可以使用帶有忽略空值的延遲來回顧每個 window 幀中的前一個非空值:

with JOINED as
(
select   b.key
        ,b.asofdate
        ,a.fees
        ,a.start_date
        ,a.end_date
from tableb b left join tablea a on b.key = a.key and b.asofdate between a.start_date and a.end_date
)
select *       
       ,case when fees is null then 
           lag(fees) ignore nulls over (partition by key order by start_date, end_date) / 3 
        else fees/3 end as fees_calc 
from JOINED
;
鑰匙 截至日期 費用 開始日期 結束日期 FEES_CALC
123 2022-08-01 100 2022-07-01 2022-09-30 33.33333333333
123 2022-09-01 100 2022-07-01 2022-09-30 33.33333333333
123 2022-10-01 null null null 33.33333333333
345 2022-09-01 200 2022-07-01 2022-09-30 66.66666666667

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM