簡體   English   中英

獲取最近30分鍾的數據並獲取最新的行

[英]Get data from last 30 minutes and get the latest rows

我有一張AIS海洋數據表,經常更新。

我需要的是過去30分鍾的數據,從那個結果來看,最新的行和MMSI應該是唯一的。

我現在的查詢:

select max(timestamp) as timestamp, mmsi, navstatus, rot, sog, lon, lat, cog,
thead, man, mtype from ais_cnb
where (timestamp > (now() - interval 30 minute))
group by mmsi
order by timestamp desc

似乎除時間戳之外的所有數據都是舊的。

如果你想要每個唯一的“mmsi”有一個最后30分鍾的最新行,那么使用連接到子查詢,你可以找到最大的時間戳首先應該工作,如:

SELECT timestamp, a.mmsi, navstatus, rot, sog, lon, lat, cog, thead, man, mtype
FROM ais_cnb a INNER JOIN
(SELECT mmsi, MAX(timestamp) AS max_timestamp FROM ais_cnb
 WHERE timestamp > (now() - interval 30 minute)
 GROUP BY mmsi) t
ON ((timestamp = t.max_timestamp) AND (a.mmsi = t.mmsi))

好吧,那里有句法錯誤。 正如我解釋這里前一段時間,你不能引用在計算領域where條款,所以你得到的時間戳實際上是領域,而不是聚合函數( max() 你沒有意識到這一點,因為你的命名方式與字段相同。 試試這個,你會看到:

select max(timestamp) as timestamp2, mmsi, navstatus, rot, sog, lon, lat, cog,
thead, man, mtype from ais_cnb
where (timestamp2 > (now() - interval 30 minute))
group by mmsi
order by timestamp desc

現在,無論您是否正確選擇這些記錄,如果您首先獲得所有最新的30分鍾數據,然后您只獲得該子集中的最新數據...是否與獲取最新數據相同數據?

此外,將所有其他字段添加到組中可能是個好主意。

或許我得錯了。 你能詳細說明嗎?

編輯:要過濾分組數據,您需要添加HAVING子句。 您之前的查詢應該按以下方式編寫(但我不確定這是否是您要查找的內容):

select max(timestamp) as timestamp2, mmsi, navstatus, rot, sog, lon, lat, cog,
thead, man, mtype from ais_cnb
group by mmsi
having (timestamp2 > (now() - interval 30 minute))
order by timestamp desc

但是,我確實認為你可能正在尋找每個組的最大最大值,這應該通過不同的查詢來解決......但正如我所說,我沒有足夠的信息來得出結論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM