2

我有一个查询,我正在处理一个项目,然后我擦除了数据集并重新开始,现在我根本无法获取任何数据。
查询基本上是:

SELECT * 
FROM   TABLEA 
       LEFT JOIN TABLEB 
              ON TABLEA.ID = TABLEB.ID 
WHERE  TABLEA.ID = 1 
       AND TABLEB.DATE = (SELECT MAX(TABLEB.DATE) 
                          FROM   TABLEB 
                          WHERE  TABLEA.ID = 1) 

TableB 跟踪更改,每个 ID 有数百个条目。我想要与该 ID 有关的最后一个按时间顺序排列的项目的单行。
如果有更好的方法来做到这一点,那就太棒了,但我真的很想知道为什么这个特定的查询不起作用。当我运行此查询时:

SELECT MAX(TABLEB.DATE) 
FROM   TABLEB 
       LEFT JOIN TABLEB 
              ON TABLEA.ID = TABLEB.ID 
WHERE  TABLEA.ID = 1 

我得到了数据集中最后一个日期的正确值。

4

2 回答 2

3
select * 
from tableA as a
    left outer join tableB as b on b.ID = a.ID
where
    b.Date = (select max(t.Date) from tableB as t WHERE t.ID = a.id)
    -- and a.ID = 1 if you need it

如果你只需要tableB中的日期,你可以做

select * 
from tableA as a
    left outer join (
        select max(t.Date) as Date, t.ID from tableB as t group by t.ID
    ) as b on b.ID = a.ID
-- where a.ID = 1 if you need it

如果您可以使用row_number函数(您可以将公用表表达式更改为子查询):

with cte as (
    select *, row_number() over(partition by a.ID order by b.Date desc) as rn
    from tableA as a
        left outer join tableB as b on b.ID = a.ID        
    -- where a.ID = 1 if you need it
)
select *
from cte
where rn = 1

如果您使用的是 SQL Server 版本 >= 2005:

select * 
from tableA as a
    outer apply (
        select top 1 t.*
        from tableB as t
        where t.ID = a.ID
        order by t.Date desc
    ) as b
-- where a.ID = 1 if you need it

请注意在所有子查询中使用别名。

关于您的初始查询,我认为您有一个错字:

SELECT * 
FROM   TABLEA 
       LEFT JOIN TABLEB 
              ON TABLEA.ID = TABLEB.ID 
WHERE  TABLEA.ID = 1 
       AND TABLEB.DATE = (SELECT MAX(TABLEB.DATE) 
                          FROM   TABLEB 
                          WHERE  TABLEA.ID = 1) -- <-- Do you mean TABLEB.ID = 1 ??
于 2013-09-09T21:00:10.773 回答
0

这是一种方法:

SELECT *
FROM tableA LEFT JOIN
     tableB
     ON tableA.ID = tableB.ID
WHERE tableA.ID = 1
ORDER BY tableB.Date desc
LIMIT 1;
于 2013-09-09T21:02:08.293 回答