繁体   English   中英

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

[英]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 返回 systems_test_status.mo_number。

在没有子查询的情况下运行它会正确返回大约 48,000 条用于压力测试电气资产的记录。 这些记录中有许多属于同一资产(其参考是 test_index)。 每个资产都经过多次测试。

单独运行子查询正确返回每个资产的最近测试日期。

我正在尝试对每个资产进行最新的测试。

谢谢

您可以使用row_number函数将最大日期行设置为 1,然后选择记录。 该解决方案假定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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM