[英]Create table with missing and present dates from fact and dim tables SQL query
給定帶有一些日期的事實表和包含所有日期的暗表,需要創建一個如下表,其中包含缺失日期和當前日期:
事實表
Fact_date
2018-01-04
2018-01-05
2018-01-22
日期
date_dt
2018-01-01
2018-01-02
2018-01-03 …
從上面的兩個表中,創建下面的這個表
Type start_date end_date
Missing 2018-01-01 2018-01-03
Present 2018-01-04 2018-01-05
Missing 2018-01-06 2018-01-22
這是我到目前為止所擁有的:
with a as (
(select date_dt as date_col,
'missing' as type
from dimdate)
union all
(select fact_date as date_col,
'present' as type
from fact_table)
),
b as (
select date_col,
type,
row_number() over (order by date_col asc) as seq
from a
)
select type,
min(date_col) as start_date, max(date_col) as end_date
from b
group by dateadd(d, -seq, date_col),type
這給了我這樣的:
Type start_date end_date
Missing 2018-01-01 2018-01-04
Present 2018-01-04 2018-01-05
Missing 2018-01-05 2018-01-22
在缺失行中,我應該將 2018-01-03 而不是 2018-01-04 作為第一行的 end_date。
有人可以幫助我正確完成此查詢嗎?
這是一種間隙和島嶼問題,但似乎相當棘手:
select (case when fact_date is null then 'Missing' else 'Present' end) as grp,
min(date_dt), max(date_dt)
from (select d.date_dt, t.fact_date,
count(fact_date) over (order by d.date_dt) as seqnum,
sum(fact_date is null) over (order by d.date_dt) as seqnum_2
from dim_date d left join
fact_table t
on d.date_dt = t.fact_date
) t
group by grp,
(case when fact_date is null then seqnum else seqnum_2 end)
order by min(date_dt);
這是一個 db<>fiddle。
這很棘手。 這個想法是為存在日期和缺少日期的組找到一個常量值。 這個想法是計算到給定日期的當前值的數量——當日期丟失時這是恆定的。 現值的類似邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.