Value should be 0 between the two dates?

强颜欢笑 提交于 2019-12-02 07:38:35

This will show value for the records present, 0 for the records missing:

SELECT  t2.id, t2.date,
        COALESCE(
        (
        SELECT  TOP 1 t2.value
        FROM    table1 t1
        WHERE   t2.date BETWEEN t1.fromdate AND t1.todate
                AND t2.id = t1.id
        ), 0) AS value
FROM    table2 t2

This will work other way around: 0 for the records present, value for the records missing:

SELECT  t2.id, t2.date,
        COALESCE(
        (
        SELECT  TOP 1 0
        FROM    table1 t1
        WHERE   t2.date BETWEEN t1.fromdate AND t1.todate
                AND t2.id = t1.id
        ), t2.value) AS value
FROM    table2 t2
select t2.id, t2.date, coalesce(T.value, 0) value
from table2 t2
left join 
     (select t22.id, t22.date, t22.value
        from table2 t22
       where not exists (select null from table1 t1
                          where t22.date between t1.fromdate and t1.todate)
     ) T on t2.id = T.id and t2.date = T.date
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!