【问题标题】:How do I join two tables in SQL limiting the second table data depending on the first one?如何在 SQL 中连接两个表,根据第一个表限制第二个表数据?
【发布时间】:2018-05-05 15:41:42
【问题描述】:

我有两张表看起来像这样:

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 中的 Cat 1 的最晚日期为 2 月)和项目“O”(因为表 1 中的 Cat 2 有最迟 4 月)。

我已经在第二个表的 where 子句中尝试了条件,但还没有走远。

有没有简单的方法来做到这一点?任何帮助表示赞赏。顺便说一句,我使用的是 SQL Server 2008。

【问题讨论】:

  • 我们能看到你目前的查询吗? DATE 列的数据类型是什么?
  • 编辑您的问题并提供示例数据和所需的结果。如果您想要两个表中的所有行,为什么要谈论 join
  • 结果可以有不同类别的行吗?

标签: sql sql-server sql-server-2008 date join


【解决方案1】:

Desire 输出及其格式仍不清楚。

你在找这个吗?

;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

【讨论】:

    【解决方案2】:

    您对问题的描述具体是关于使用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;
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 2016-07-21
      • 2020-04-08
      相关资源
      最近更新 更多