![](/img/trans.png)
[英]getting latest timestamp from 2 joined tables for each row output in select statement
[英]Join two tables. Use a joined column as Group By to then select the latest row based on timestamp
我有兩張桌子:
連接器狀態
連接器 | 狀態時間戳 | 地位 |
---|---|---|
1個 | 2020-03-03 09:07:09.058000 | 可用的 |
2個 | 2020-03-03 09:51:03.852000 | 故障 |
1個 | 2022-10-06 16:32:14.130000 | 收費 |
3個 | 2022-10-06 16:28:26.228000 | 可用的 |
4個 | 2022-10-06 16:28:03.195000 | 收費 |
連接器
連接器 | box_id | connector_id |
---|---|---|
1個 | Α | 0 |
2個 | Α | 1個 |
3個 | 測試版 | 0 |
4個 | 測試版 | 1個 |
我的 connector_status 表中的每個連接器都有多行,但我只想要基於 box_id 的最新行
我想加入基於 box_id 的表,但使用來自 2x 連接器的最新時間戳。 這將 select status 根據上表計費
聯接表看起來有點像這樣:
連接器 | 狀態時間戳 | 地位 | box_id |
---|---|---|---|
1個 | 2020-03-03 09:07:09.058000 | 可用的 | Α |
2個 | 2020-03-03 09:51:03.852000 | 故障 | Α |
1個 | 2022-10-06 16:32:14.130000 | 收費 | Α |
3個 | 2022-10-06 16:28:26.228000 | 可用的 | 測試版 |
4個 | 2022-10-06 16:28:03.195000 | 收費 | 測試版 |
有了想要的結果:
box_id | 地位 |
---|---|
Α | 收費 |
測試版 | 可用的 |
我有以下代碼
SELECT IF(connector_status.status = 'Charging','Charging', IF(connector_status.status ='Available','Not Occupied', IF(connector_status.status = 'Faulted','Faulted','Occupied'))) AS group_status, connector.connector_id, connector.box_id, status_timestamp FROM connector_status JOIN connector ON connector_status.connector = connector.connector GROUP BY connector.box_id ORDER BY connector.box_id
我不知道如何在 box_id 上進行連接以獲得最大時間戳。
令我困惑的是,如果我首先從 connector_status 表中獲取最新的時間戳,然后嘗試通過 box_id 加入,我怎么能確定它將采用該 box_id 的最新連接器時間戳
您可以使用 row_number 來獲得所需的結果:
select box_id,
status
from ( select status,
box_id,
row_number() over( partition by tbl.box_id order by tbl.status_timestamp desc ) as rn
from ( select status_timestamp,
status,
box_id
from connector_status cs
inner join connector c on c.connector=cs.connector
) as tbl
) as x where rn=1 ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.