【问题标题】:Select the last to a certain date record from the dependent table从依赖表中选择最后到某个日期的记录
【发布时间】:2021-04-01 11:39:14
【问题描述】:

在 SQL Server 中我有 2 个表

table_a

card_number reissue_date
1           15.02.2017 00:00:00
2           01.02.2017 00:00:00
3           01.01.2017 00:00:00

table_b

card_number timestamp               limit
1           01.01.2017 00:00:00     9999
1           01.02.2017 00:00:00     100000
1           01.03.2017 00:00:00     25000
2           01.01.2017 00:00:00     10001
3           01.03.2017 00:00:00     5000
3           01.04.2017 00:00:00     0

预期结果

card_number limit
1           100000
2           10001

我尝试了很多选项,我接近解决方案,但我无法显示“限制”列,解决这个问题的最佳方法是什么?

我的错误决定

SELECT table_b.card_number, Max(timestamp)
FROM   table_b LEFT JOIN table_a
  ON ( table_b.card_number = table_a.card_number
   AND table_b.timestamp < table_a.reissue_date )
WHERE  table_a.reissue_date IS NOT NULL
GROUP  BY table_b.card_number;

必须选择table_b表的最新按日期记录,但不能大于table_a中的日期

我目前找到的可行解决方案,我不确定它是否正常工作,但根据我的初始数据,它给出了预期的结果

SELECT card_number, 
       Max(timestamp), 
       Max(limit) AS timestamp 
FROM   table_b 
WHERE  table_b.timestamp < (SELECT reissue_date 
                            FROM   table_a 
                            WHERE  card_number = table_b.card_number) 
GROUP  BY card_number;

【问题讨论】:

  • 请粘贴文本而不是屏幕截图
  • 请用您正在运行的数据库标记您的问题:mysql、oracle、sql-server...?
  • 您能更好地描述所需的输出吗?你的解释没有道理。
  • 对不起,我需要获取卡的最后设置限制,不包括日期大于第一个表日期的卡
  • 为什么要 10 万美元买卡 #1?不应该是 25,000 美元吗?

标签: sql sql-server datetime subquery lateral-join


【解决方案1】:

在 SQL Server 中,我们可以使用行限制横向连接来将第二张表中的最新记录带到第一张表的时间戳之前:

select a.card_number, b.*
from table_a a
cross apply (
    select top (1) b.*
    from table_b b 
    where b.card_number = a.card_number and b.timestamp < a.reissue_date 
    order by b.timestamp desc
) b

这也消除了不匹配的行,这与您的数据一致。

【讨论】:

  • 这正是你需要的,非常感谢
  • @TheImpaler:需要选择table_b表的最新按日期记录,但不能大于table_a中的日期。但 OP 的查询确实讲述了一个不同的故事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多