[英]How to get max(column value) based on another column value
I have a table with following schema and sample values. 我有一个包含以下架构和示例值的表。
I am trying to write a query which will give me for each user its max(timestamp) for connected status as well as disconnected status. 我正在尝试编写一个查询,该查询将为每个用户提供连接状态以及断开状态的max(timestamp)。
Example of the output schema for the required query I am looking for is: 我正在寻找所需查询的输出模式示例为:
Username | 用户名| Connected_MAX_Timestamp | Connected_MAX_Timestamp | Disconnected_MAX_Timestamp Disconnected_MAX_Timestamp
The query which I tried is this : 我尝试过的查询是这样的:
SELECT username,socketstatus,max(timestamp) from socketinfo group by username,socketstatus 从套接字信息组中按用户名,socketstatus选择用户名,socketstatus,max(timestamp)
and the output for the same is : 和相同的输出是:
Can someone tell me how to achieve the required output ? 有人可以告诉我如何实现所需的输出吗?
Just use conditional aggregation: 只需使用条件聚合:
select username,
max(case when socketstatus = 'Connected' then timestamp end) as max_connected_timestamp,
max(case when socketstatus = 'Disconnected' then timestamp end) as max_disconnected_timestamp,
from socketinfo
group by username;
SELECT t1.username,
t1.socketstatus,
max(t1.timestamp) AS "Connected_MAX_Timestamp",
t2.username,
t2.socketstatus,
max(t2.timestamp) "Disconnected_MAX_Timestamp"
FROM socketinfo t1,
socketinfo t2
WHERE t1.socketstatus='Connected'
AND t2.socketstatus='Disconnected'
AND t1.username=t2.username
GROUP BY t1.username,
t1.socketstatus,
t2.username,
t2.socketstatus;
This works on Postgres 9.5, if I understood your question correctly. 如果我正确理解了您的问题,则此方法适用于Postgres 9.5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.