SQL 获取最大日期并加入其他 table

SQL get max date and join on other table

抱歉,这有点重复,但我已经完成了其他答案,这些答案帮助我找到了下面的 SQL,但我无法弄清楚如何管理与获得的子查询的连接最大日期。

SELECT
mo_number, -- from systems_test_status, everything else from combiner_test_data
CDT.test_index,
CDT.datetime,
lumina_current_1,
power_reading_1,
lumina_current_2,
power_reading_2,
lumina_current_3,
power_reading_3,
lumina_current_4,
power_reading_4
most_recent,
step_pass_status

FROM combiner_test_data AS CDT

INNER JOIN systems_test_status ON CDT.test_index = systems_test_status.test_index

--JOIN(select
--  test_index,
--  MAX(datetime) AS most_recent_time
--  FROM combiner_test_data AS subCDT
--  GROUP BY test_index) as joinCDT on CDT.test_index = joinCDT.test_index
--  and CDT.datetime = joinCDT.most_recent_time

WHERE lumina_current_2 > 12

连接和子查询单独工作正常,但它们一起只输出几行,而我期望几千行。我已经在上面的例子中注释掉了子查询。我需要内部连接的唯一原因是通过在 test_index.

上加入 return systems_test_status.mo_number

运行 它没有正确的子查询 return 大约 48,000 条记录用于压力测试电力资产。其中许多记录都属于同一资产(其参考文献是 test_index)。每个资产都经过多次测试。

运行 单独的子查询正确 return 是每项资产的最近测试日期。

我正在尝试获取每项资产的最新测试。

谢谢

您可以使用 row_number 函数将最大日期行设置为 1,然后 select 记录。该解决方案假定 mo_number 唯一标识每个资产。如果不是,请将row_number函数中的partition by更改为唯一标识资产的列。

select * from
(
SELECT
mo_number, 
combiner_test_data
CDT.test_index,
CDT.datetime,
lumina_current_1,
power_reading_1,
lumina_current_2,
power_reading_2,
lumina_current_3,
power_reading_3,
lumina_current_4,
power_reading_4
most_recent,
step_pass_status,
row_number() over(partition by mo_number order by datetime desc) as rn
FROM combiner_test_data AS CDT
INNER JOIN systems_test_status ON CDT.test_index = systems_test_status.test_index
WHERE lumina_current_2 > 12
) t
where rn = 1;