我有一个表,我需要将数据从 (Log) 复制到另一个表 (BigTable)。 Log表得到以下数据:

   LogID   LogTime             JobNumber    LogType   Description
   =====   =======             =========    =======   ===========
   1       2012-09-01 00:00:01   1          100       Accepted by D#12
   2       2012-09-01 00:05:33   1          100       Accepted by D#14
   3       2012-09-01 01:00:14   2          107       Message sent
   4       2012-09-01 05:00:53   2          100       Accepted by D#78
   5       2012-09-01 05:01:55   1          110       POB at Stop 1
   6       2012-09-01 05:02:22   3          100       Accepted by D#98
   7       2012-09-01 05:03:00   1          110       POB at Stop 2
   8       2012-09-01 05:04:00   2          110       POB at Stop 1
   9       2012-09-01 05:05:25   3          110       POB at Stop 1
  10       2012-09-01 05:15:36   1          200       Completed
  11       2012-09-01 05:20:45   2          200       Completed

以下数据已经在BigTable中
   JobNumber     Accepted_At     POB_At       Completed
   =========     ===========     ======       =========
    1            NULL            NULL         NULL
    2            NULL            NULL         NULL
    3            NULL            NULL         NULL

我正在尝试使用 Log 中的值更新 BigTable。请注意,如果出现 LogID 1 和 2(以上)等重复条目,我只会获取最新日期 (2012-09-01 00:05:33)。 POB 也是如此,因为我们只对“POB at Stop 1”感兴趣。

Log 中有数百万行用于许多作业编号,但是,我只需要为 BigTable 中的那些作业腾出时间。
理想表(所有更新后)将如下所示:
   JobNumber   Accepted_At            POB_At                  Completed
   =========   ===========            ======                  =========
    1          2012-09-01 00:05:33    2012-09-01 05:01:55     2012-09-01 05:15:36
    2          2012-09-01 05:00:53    2012-09-01 05:04:00     2012-09-01 05:20:45
    3          2012-09-01 05:02:22    2012-09-01 05:05:25     NULL

请注意,我是这个领域的新手。任何帮助表示赞赏。
提前致谢。
问候

最佳答案

您可以在 CTE 中聚合 MAX 日期,然后将其加入 BigTable 以进行更新:

; WITH CTE AS (
    SELECT
    g.JobNumber
    , Accepted_At = MAX(CASE WHEN LogType = 100 THEN LogTime END)
    , POB_At = MAX(CASE WHEN LogType = 110 AND [Description] LIKE '%Stop%1' THEN LogTime END)
    , Completed = MAX(CASE WHEN LogType = 200 THEN LogTime END)
    FROM [Log] g
    GROUP BY g.JobNumber, g.LogType
)
UPDATE b
SET Accepted_At = CTE.Accepted_At
, POB_At = CTE.POB_At
, Completed = CTE.Completed
FROM CTE
JOIN BigTable b ON b.JobNumber = CTE.JobNumber

关于sql-server-2008 - 从插入语句中的子查询(超过 1 条记录)获取最新日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12498010/

10-12 19:19