簡體   English   中英

如何在SQL中聯接兩個表,以根據第一個表限制第二個表數據?

[英]How do I join two tables in SQL limiting the second table data depending on the first one?

我有兩個看起來像這樣的表:

IMP DATE        CAT
A   03/03/2016  1
B   04/04/2016  1
C   09/09/2016  2
D   01/01/2017  1
E   02/02/2017  1
F   03/03/2017  2
G   04/04/2017  2

===================

EXP DATE        CAT
H   01/01/2016  1
I   05/05/2016  1
J   07/07/2016  2
K   11/11/2016  2
L   01/01/2017  1
M   03/03/2017  1
N   04/04/2017  2
O   05/05/2017  2

我想將第一個表連接到第二個表,但要限制從第二個表連接的行在第一個表上的最新日期(每個類別)。

我要查找的結果將是兩個表中的每一行,除了項目“ M”(因為表1中的類別1的最新日期是2月)和項目“ O”(因為表1中的類別2的最新日期是2月)四月)。

我已經在第二張表的where子句中嘗試過conditionalds,但距離還很遠。

有沒有簡單的方法可以做到這一點? 任何幫助表示贊賞。 我正在使用SQL Server 2008。

您對問題的描述專門關於使用join 這表明這樣的查詢:

select . . . 
from (select t1.*, max(t1.date) over (partition by t1.cat) as maxdate
      from table1 t1
     ) t1 join
     table2 t2
     on t1.cat = t2.cat and t2.date <= t1.maxdate;

期望輸出及其格式仍不清楚。

你在找這個嗎?

;With CTE as
(
select *, row_number()over(partition by cat order by DATEs desc) rn
from @table1
)
--select * from cte
--where rn=1

select * from cte t1
left join @table2 t2
on t1.CAT=t2.CAT and t2.DATEs<=t1.DATEs
where rn=1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM