【问题标题】:Join Table B to Table A, where Table B is an audit history, and only want the most recent Table B entry that is before a date on Table A将表 B 连接到表 A,其中表 B 是审计历史记录,并且只需要表 A 上某个日期之前的最新表 B 条目
【发布时间】:2019-07-18 00:34:10
【问题描述】:

SQL Server 2008 R2(是的,我们已经过了扩展支持日期)

表 A 有一个 VendorID 和一个日期。每个 VendorID 仅出现一次。

表 B 的 sn-p 如下。表 B 可以多次具有相同的 VendorID,但日期不同。 (它显示了 VendorID 状态的历史记录。)

如何将表 B 连接到表 A,以便获得表 B 的最新条目,该条目小于表 A 中该行的日期?

假设我只想“给我表 B 中的最新条目,按供应商 ID,即在数据 'yyyy-mm-dd' 之前 - 还不错。我可以使用窗口函数,然后加入它到表 A。

但我不想为单个日期执行此操作,数据会因表 A 行中的日期而异。

-- 例如,如果我在 set 日期之前按 VendorId 从表 B 中获取最新条目。然后我可以加入结果,没问题。

select 
    sq.VendorId
    ,sq.PaymentType

from ( 
    select 
        a.VendorId
        ,a.PaymentType
        ,row_number() over (partition by a.vendorid order by createdateutc 
 desc) as rn 

from  
    ZpCustomers_Kim.dbo.VendorListPaymentTypeChangeAudit a  --**Table B**

WHERE 
    CreateDateUTC < '2019-05-09' 

 ) sq

where 
    sq.rn = 1

但是,如果我想不使用“2019-05-19”,而是让日期取决于 表 A 行中的日期,我该怎么做?

【问题讨论】:

    标签: sql tsql


    【解决方案1】:

    我不确定您的查询与该问题有什么关系。但是你可以用apply做你想做的事:

    select a.*, b.*
    from a outer apply
         (select top (1) b.*
          from b
          where b.VendorID = a.VendorID and
                b.date <= a.date
          order by d.ate desc
         ) b;
    

    【讨论】:

    • 我必须修正我的格式(因此,查询可能看起来不相关),但我认为就是这样 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多