【问题标题】:Update fields with an ID that is driven by date range使用由日期范围驱动的 ID 更新字段
【发布时间】:2019-07-31 09:44:40
【问题描述】:

我在SQL 有两张桌子: T1 布局如下:

PrID       NapID       URN       Date
-------------------------------------------
12345   |  NULL    |   123    |  2019-06-02
23456   |  NULL    |   456    |  2019-07-03
34567   |  NULL    |   789    |  2019-07-05

T2 布局如下:

SYSApID    PnID     StartDate    EndDate
-------------------------------------------
54321   |  2     |  2019-06-01 | 2019-06-30
65432   |  3     |  2019-07-01 | 2019-07-31

我希望获得有关如何使用来自table 2SYSApID 更新table 1 中的NapID 列的指针,它将根据@ 的位置应用相关的ID table 1 中的 987654329@ 介于 table2 中的 StartDateEndDate 之间。

【问题讨论】:

  • 标记您的 dbms 名称

标签: sql join sql-update


【解决方案1】:

先前答案的混合

UPDATE
    t1
SET 
    NapID = t2.SYSApID
FROM
    t1
    JOIN t2 ON t1.date between t2.StartDate and t2.EndDate

【讨论】:

    【解决方案2】:

    您没有指定您的 DBMS,因此此答案适用于 SQL SERVER。

    update t1
    set t1.napID = (select top 1 t2.SYSApID from table2 t2 where t1.[Date] between t2.StartDate and t2.EndDate)
    from table1 t1
    

    【讨论】:

      【解决方案3】:

      试试这个:

      UPDATE t1
        SET 
            t1.napid = t2.sysapid
      FROM t1
           JOIN t2 ON t2.startdate = CONVERT(VARCHAR(10), DATEADD(month, DATEDIFF(month, 0, date), 0), 120)
      

      【讨论】:

      • 我认为你不需要在t1.napid = t2.sysapid中写t1
      【解决方案4】:

      您可以在下面尝试,这在 Oracle 中有效:-

      update t1  
      set  t1.napID = (select t2.sysappid from t2 where t1.date between t2.start_date and t2.End_date and rownum <2);
      

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 2020-05-23
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        相关资源
        最近更新 更多