2015-10-22 45 views
-1

對不起,這是有點重複,但我已經通過其他答案,幫助我到達SQL下面,但我不明白如何管理與子查詢獲取最大日期。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)。每項資產都經過多次測試。

單獨運行子查詢會正確返回每個資產的最近測試日期。

我想爲每個資產得到最新的測試。

感謝

+1

你爲什麼期望幾千? –

+1

通過INNER JOIN添加回該子查詢應該僅爲每個test_index提供'combiner_test_data',其中'datetime'只是最近的'datetime'。也許......你並不是想要最近一次,而是最近一次有很多次「約會」?這只是一個猜測,因爲沒有足夠的信息來幫助你。我們需要查看一些示例數據以及此查詢的預期輸出以正確診斷。 – JNevill

+0

對不起,OP更新爲清晰。謝謝。 – Absinthe

回答

1

可以使用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; 
相關問題