Select Query with ID and Last Date Validation



使用SQL Server 2000

表1:

ID LastDate
001 20090101
003 20090501
004 20090302
...

表:

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
...

我想从表2中选择id和日期,日期应该从表1的下一个日期开始显示。

查询:

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

我想对上述条件进行查询

试一试:

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
)

看来这里需要的是反连接。例如,您可以使用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
)

最新更新