SQL-根据最新条目连接两个表

时间:2019-03-14 11:19:43

标签: sql-server stored-procedures

我有两个桌子

1- TestModules表

TestModules

enter image description here

2- TestModule_Results表

TestModule_Results

enter image description here

为了获得每个TestModule所需的信息,我正在使用FULL OUTER JOIN,并且工作正常。

FULL OUTER JOIN结果

enter image description here

但是所需的内容略有不同。上图显示TestModuleID = 5被列出两次,并且要求基于时间'ChangedAt'列出“最新”结果

我当然可以执行以下操作:

SELECT TOP 1 * FROM TestModule_Results
WHERE DeviceID = 'xxx' and TestModuleID = 'yyy'
ORDER BY ChangedAt DESC

但是此解决方案仅适用于一行,我想在存储过程中进行。

预期输出应为: ExpectedOutput

有人建议如何在SP中实现它?

2 个答案:

答案 0 :(得分:0)

您说“此解决方案适用于单行”吗?优秀。使用CROSS APPLY并将WHERE子句从手工输入文字更改为原始表的字段。 APPLY在行级进行操作。

SELECT *
FROM TestModules t
CROSS APPLY
(
    SELECT TOP 1 * FROM TestModule_Results
    WHERE TestModule_Results.DeviceID = TestModules.DeviceID -- put the connecting fields here
    ORDER BY ChangedAt DESC
)tr

答案 1 :(得分:0)

使用“公共表表达式”和“行号”添加一个标识最新结果的字段(如果有的话),然后为这些结果选择一个

--NOTE: a Common Table Expression requires the previous command
--to be explicitly terminiated, prepending a ; covers that
;WITH cteTR as (
    SELECT * 
        , ROW_NUMBER() OVER (PARTITION BY DeviceID, TestModuleID 
            ORDER BY ChangedAt DESC) AS ResultOrder
    FROM TestModule_Results
    --cteTR is now just like TestModule_Results but has an 
    --additional field ResultOrder that is 1 for the newest, 
    --2 for the second newest, etc. for every unique (DeviceID,TestModuleID) pair
)
SELECT * 
FROM TestModules as M  --Use INNER JOIN to get only modules with results, 
  --or LEFT OUTER JOIN to include modules without any results yet
  INNER JOIN cteTR as R
    ON M.DeviceID = R.DeviceID AND M.TestModuleID = R.TestModuleID
WHERE R.ResultOrder = 1 
-- OR R.ResultOrder IS NULL --add if Left Outer Join