使用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,日期,来自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
如何查询这种情况?
这将显示value存在0的记录,缺少的记录:
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