我有一个查询,我已经处理了一个项目,然后我擦除了数据集并重新开始,现在我根本无法获取任何数据。
查询基本上是:
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
我得到数据集中最后一个日期的正确值。
答案 0 :(得分: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 ??
答案 1 :(得分:0)
这是一种方式:
SELECT *
FROM tableA LEFT JOIN
tableB
ON tableA.ID = tableB.ID
WHERE tableA.ID = 1
ORDER BY tableB.Date desc
LIMIT 1;