Value should be 0 between the two dates?

后端 未结 2 1365
耶瑟儿~
耶瑟儿~ 2021-01-27 14:48

Using SQL Server 2000

I want to compare the table2.date between table1.from, table1.todate, if exist then value should be 0 (zero)

Table1

ID From         


        
2条回答
  •  死守一世寂寞
    2021-01-27 15:13

    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
    

提交回复
热议问题