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

时间:2015-06-30 21:12:27

标签: sql sql-server subquery distinct

在SQL Server中,我有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脚本提取一个条目,并将其与仅在SCRIPT HISTORY中最近的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

2 个答案:

答案 0 :(得分:0)

您描述问题的方式几乎就是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;

答案 1 :(得分:0)

请尝试这样的事情:

    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