繁体   English   中英

连接两个表。 使用连接列作为 Group By 然后 select 基于时间戳的最新行

[英]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 ;

https://dbfiddle.uk/1LRcbbma

暂无
暂无

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

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