选择带有ID和上次日期验证的查询

时间:2011-11-14 05:51:24

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

使用SQL Server 2000

表1:

ID LastDate

001 20090101
003 20090501
004 20090302
...

表2:

ID Date Value

001 20090101 100
001 20090102 200
001 20090103 200
002 20090101 350
002 20090302 500
003 20090501 200
003 20090502 250
004 20090302 400
...

从table2我想选择id和日期,日期应该从table1开始显示从下一个日期开始。

查询如下:

Select * from table2 where date > table1.last on table1.id = table2.id

预期产出:

ID Date Value

001 20090102 200
001 20090103 200
002 20090101 350
002 20090302 500
003 20090502 250
...

从上面的输出中,

id 001 is displaying from the next date of table1.lastdate
id 002 is displaying the same date because 002 is not in table1
id 003 is displaying from the next date of table1.lastdate
id 004 is not displaying because the same date is available on table1.lastdate

我想查询上述情况。

2 个答案:

答案 0 :(得分:1)

试一试:

Select * from table2 t2 where t2.date > (select max(date) from table1 t1 where t1.id = t2.id)

编辑:

SELECT * FROM Table2 t2
WHERE t2.Date > 
(
    SELECT ISNULL(maxdate, 0) FROM 
    (
        SELECT MAX(t1.Date) as maxdate FROM Table1 t1 WHERE t1.ID = t2.ID
    ) t
)

答案 1 :(得分:0)

看起来像反连接就是你需要的。例如,您可以使用LEFT JOIN&来实现反加入。 IS NULL检查:

SELECT
  t2.columns
FROM table2 t2
  LEFT JOIN table1 t1 ON t2.ID = t1.ID AND t2.Date <= t1.Date
WHERE t1.ID IS NULL

另一种方法是使用NOT EXISTS

SELECT
  columns
FROM table2 t2
WHERE NO EXISTS (
  SELECT *
  FROM table1 t1
  WHERE t2.ID = t1.ID
    AND t2.Date <= t1.Date
)