如何根据另一个 table 中的值将一个不同 table 中的特定值添加到一行中的列?

How do I add specific values from one different table to columns in a row based off of values in another table?

在 SQL 服务器中,我有 2 个表,如下所示:

TEST SCRIPT    'a collection of test scripts'
(PK)
ID   Description   Count
------------------------
A12  Proj/Num/Dev  12
B34  Gone/Tri/Tel  43
C56  Geff/Ben/Dan  03

SCRIPT HISTORY 'the history of the aforementioned scripts'
(FK)      (PK)
ScriptID  ID   Machine    Date    Time    Passes
----------------------------------
A12       01   DEV012     6/26/15 16:54   4
A12       02   DEV596     6/28/15 13:12   9
A12       03   COM199     3/12/14 14:22   10
B34       04   COM199     6/30/13 15:45   12
B34       05   DEV012     6/30/15 13:13   14
B34       06   DEV444     6/12/15 11:14   14
C56       07   COM321     6/29/14 02:19   12
C56       08   ANS042     6/24/14 20:10   18
C56       09   COM432     6/30/15 12:24   4
C56       10   DEV444     4/20/12 23:55   2

在单个查询中,我将如何编写一个 select 语句,该语句只为 TEST SCRIPT 中的每个 DISTINCT 脚本获取一个条目,并将其与仅 TOP 1 最近的值配对 运行 脚本历史中的时间?

例如,上面示例表的解决方案是:

OUTPUT
ScriptID    ID    Machine    Date    Time    Passes
---------------------------------------------------
A12         02    DEV596     6/28/15 13:12   9
B34         05    DEV012     6/30/15 13:13   14
C56         09    COM432     6/30/15 12:24   4

您描述问题的方式几乎直接为 cross apply:

select h.*
from testscript ts cross apply
     (select top 1 h.*
      from history h
      where h.scriptid = ts.id
      order by h.date desc, h.time desc
     ) h;

请尝试这样的操作:

    select * 
    from SCRIPT SCR
         left join (select MAX(SCRIPT_HISTORY.Date) as Date, SCRIPT_HISTORY.ScriptID 
                    from SCRIPT_HISTORY 
                    group by SCRIPT_HISTORY.ScriptID 
                    ) SH on SCR.ID = SH.ScriptID