簡體   English   中英

來自兩個表的兩個最大日期時間值的 Datediff,並根據差異更新第三個表

[英]Datediff of two max datetime values from two tables and update a third table based on the difference

我有三個表 Account、Solditems 和 Appointments。

當相關的 SoldItems 和 Appointments 表中的日期差異大於 6 年時,我需要更新每個 Account 行的 IsOverSixYears 列。

一個賬戶可以有多個Solditems和多個Appointments,所以我需要找到最新銷售的物品和最近的約會並比較它們,IsOverSixYears標志應該根據帳戶最新銷售的物品和約會設置。

這是我的嘗試,它給了我不好的結果:

    Update AccountBase
    Set  IsOverSixYears=0
    Update AccountBase 
    Set  IsOverSixYears= Case
     WHEN   ABS(DATEDIFF(DAY,(Select Top (1) Si.SellDate order by Si.SellDate desc),(Select 
     Top(1)app.AppointmentDate order by app.AppointmentDate desc)))< 6*365 
      THEN 1
     WHEN   ABS(DATEDIFF(DAY,(Select Top (1) Si.SellDate),(Select Top(1)app.AppointmentDate)))>= 6*365 
      THEN 0
     END
    FROM [dbo].[AccountBase] acc inner join [dbo].[SoldItems] Si on acc.accountnumber = Si.accountnumber
 inner join Appointments app on acc.AccountId=app.accountId

我認為內部 select 是問題,因為這個查詢給我的結果就像內部查詢忽略了 order by 子句:

Select Si.SellDate,app.AppointmentDate, 
(Select Top (1) Si.SellDate order by Si.SellDate desc) as Latest 
FROM [dbo].[AccountBase] acc inner join [dbo].[SoldItems] Si on acc.accountnumber = Si.accountnumber
       inner join Appointments app on acc.AccountId=app.accountId
       Where Si.accountnumber='V033072'

結果:

SellDate                AppointmentDate         Latest
2006-07-06 00:00:00.000 2017-08-17 09:00:00.000 2006-07-06 00:00:00.000
2006-07-06 00:00:00.000 2017-08-17 09:00:00.000 2006-07-06 00:00:00.000
2011-08-08 00:00:00.000 2017-08-17 09:00:00.000 2011-08-08 00:00:00.000
2017-08-17 00:00:00.000 2017-08-17 09:00:00.000 2017-08-17 00:00:00.000
2011-08-08 00:00:00.000 2017-08-17 09:00:00.000 2011-08-08 00:00:00.000

它與 Selldate 沒有什么不同。

我已經在日期時間字段上嘗試了 Max function 但它給了我運行時錯誤:

聚合可能不會出現在 UPDATE 語句的集合列表中。

如何重寫此查詢以正常工作?

謝謝您的幫助。

嗯。 . . 您可以在加入之前使用FROM子句和聚合。 您想要的邏輯如下所示:

update ab
    set IsOverSixYears = (case when AppointmentDate > dateadd(year, 6, max_SellDate) then 1 else 0 end)
    from AccountBase ab left join
         (select si.accountId, max(si.SelltDate) as max_SellDate
          from Solditems si
          group by accountId
         ) si
         on si.accountId = ab.accountId left join
         (select a.accountId, max(a.AppointmentDate) as max_AppointmentDate
          from Appointments a
          group by accountId
         ) a
         on a.accountId = ab.accountId ;

您的問題沒有指定如果缺少日期該怎么辦。 甚至不知道這 6 年的發展方向是什么,但這假設sellDate是較舊的日期。

暫無
暫無

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

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