Sql 在select语句中获取每个组的最新条目
我有3个表要连接以获得table1.code、table1.series、table2.entry\u date、table3.title1 我正在尝试获取最新的非空table3.title1,按table1.code和table1.series分组Sql 在select语句中获取每个组的最新条目,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有3个表要连接以获得table1.code、table1.series、table2.entry\u date、table3.title1 我正在尝试获取最新的非空table3.title1,按table1.code和table1.series分组 select table1.code, table1.series, max(table2.entry_date), table3.Title1 from table3 INNER JOIN table2 ON
select table1.code, table1.series, max(table2.entry_date), table3.Title1
from table3 INNER JOIN table2 ON table3.ID = table2.ID
INNER JOIN table1 ON table2.source_code = table1.code
where table3.Title1 is not NULL
group by table1.code, table1.series, table3.Title1
似乎给了我所有标题为非空的条目,而不是最近的条目。我应该如何构造查询,以便只为每个代码和系列选择标题1的最新版本 试试这个:
select table1.code, table1.series, max(table2.entry_date), max(table3.Title1) as Title1
from table3
INNER JOIN table2 ON table3.ID = table2.ID
INNER JOIN table1 ON table2.source_code = table1.code
where table3.Title1 is not NULL
And Table2.entry_Date = (Select Max(sq.entry_Date)
From sq.table2
Where sq.id = table2.ID)
group by table1.code, table1.series
也许像这样的东西只加入到最新的table2条目中
SELECT
table1.code,
table1.series,
table2.entry_date,
table3.Title1
FROM
table1
INNER JOIN
table2
ON
table2.source_code = table1.code
AND
table2.entry_date =
(
SELECT
MAX(maxtable2.entry_date)
FROM
table2 maxtable2
WHERE
maxtable2.source_code = table2.source_code
)
INNER JOIN
table3
ON
table3.ID = table2.ID
这可能非常快,具体取决于您的索引。它给出了最近的日期,但没有添加相应的最近标题。可能您需要更改表的顺序;所以从表1中选择,然后加入表2和表3。你能发布一些DDL和样本数据吗?你能提供一些样本数据吗?
;with tlb as
(
select table1.code, table1.series, table2.entry_date, table3.Title1,
row_number() over(code, series, entry_date order by code, series, entry_date desc) as rn
from table3 INNER JOIN table2 ON table3.ID = table2.ID
INNER JOIN table1 ON table2.source_code = table1.code
where table3.Title1 is not NULL
)
select * from tlb where rn = 1