我有两个表,其中一个包含代码及其对应的显示名称,另一个表包含其结果和历史记录。
表1:
code name
101 provide
102 modify
103 cease
104 cancel
表2:
code result environment date time
101 Pass test 16/08/2019 06:19:35
102 Pass acc 15/08/2019 06:19:35
101 Pass test 16/08/2019 07:19:35
103 Fail test 14/08/2019 06:19:35
102 Pass test 12/08/2019 10:19:35
104 Pass acc 13/08/2019 20:19:35
我想选择特定于环境和代码的最新记录,并显示如下,
code name result date time
101 provide Pass 16/08/2019 06:19:35
102 modify Pass 12/08/2019 10:19:35
103 cease Fail 14/08/2019 06:19:35
我对MSSQL很陌生。
可以请你帮忙。
预先感谢
答案 0 :(得分:0)
您的查询应该是这样的:
WITH cte AS (
SELECT t2.code, t2.name , t2.result , t2.date, t2.time
ROW_NUMBER() (PARTITION BY t2.environment, t2.code ORDER BY date desc, time desc) rn
FROM table1 t1
LEFT JOIN table2 t2 ON t1.code=t2.code
)
SELECT
*
FROM cte
WHERE rn = 1;
答案 1 :(得分:0)
以下查询将为您提供所需的结果:
SELECT * FROM
(
SELECT code, name , environment, result , [date], [time]
ROW_NUMBER() OVER (PARTITION BY environment, Code ORDER BY [Date] desc, [Time] desc) rn
FROM table1 t1
LEFT JOIN table2 t2 ON t1.code=t2.code
) AS T
Where T.rn = 1