两个日期之间的值应为0?

时间:2009-10-08 12:08:27

标签: sql sql-server tsql sql-server-2000

使用SQL Server 2000

我想比较table1.from,table1.todate之间的table2.date,如果存在则值应为0(零)

表1

ID FromDate ToDate

001 20090801 20090815
002 20090817 20090820
…,

表2

Id Date Value

001 20090730 100
001 20090731 200
001 20090801 300
001 20090802 400
…
001 20090815 0
001 20090816 250
…

从上面两个表中我想要ID,Date,table2中的值,其中table2.date介于table1.fromdate和table1.todate之间,然后是table2.value = 0

预期产出

Id Date Value

001 20090730 100
001 20090731 200
001 20090801 0
001 20090802 0
…

001 20090815 0
001 20090816 250

如何查询此情况?

2 个答案:

答案 0 :(得分:1)

这将显示value显示的记录,0显示缺失的记录:

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

这将以其他方式工作:对于存在的记录0,对于缺失的记录value

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

答案 1 :(得分:0)

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