我当前的SQL代码:
SELECT
[Date], [Count]
FROM
Calendar_Table pdv
LEFT JOIN
(SELECT
COUNT([FILE NAME]) AS [Count], [CLOSE DT]
FROM
Production_Table
GROUP BY
[CLOSE DT]) [Group] ON [pdv].[Date] = [Group].[CLOSE DT]
ORDER BY
[Date]
请参阅下面的代码。Calendar_Table
是一个简单的表,每个日期对应一行。Production_Table
给出了每天销售的产品。如果左联接生成NULL
,请生成最新的非NULL
值。
电流输出:
Date | Count
-----------+--------
9/4/2019 | NULL
9/5/2019 | 1
9/6/2019 | 4
9/7/2019 | NULL
9/8/2019 | 7
9/9/2019 | 11
9/10/2019 | NULL
9/11/2019 | 14
9/12/2019 | NULL
9/13/2019 | 19
期望输出:
Date | Count
-----------+--------
9/4/2019 | 0
9/5/2019 | 1
9/6/2019 | 4
9/7/2019 | 4
9/8/2019 | 7
9/9/2019 | 11
9/10/2019 | 11
9/11/2019 | 14
9/12/2019 | 14
9/13/2019 | 19
一个选项是横向连接:
select c.date, p.*
from calendar_table c
outer apply (
select top (1) count(file_name) as cnt, close_dt
from production_table p
where p.close_dt <= c.date
group by p.close_dt
order by p.close_dt desc
) p
作为一种替代方案,我们可以使用equi-join来带来匹配的日期,就像在原始查询中一样,然后用窗口函数填补空白。基本的想法是建立小组,每次比赛时都会重置。
select date, coalesce(max(cnt) over(partition by grp), 0) as cnt
from (
select c.date, p.cnt,
sum(case when p.close_dt is null then 0 else 1 end) over(order by c.dt) as grp
from calendar_table c
left join (
select close_dt, count(file_name) as cnt
from production_table p
group by close_dt
) p on p.close_dt = c.date
) t
根据您的数据,一个或另一个解决方案的性能可能会更好。