简体   繁体   English

我想在 postgres SQL 中按日期和时间对我的数据进行分组,并希望每个 groupby 列中有一行

[英]I want to group by my data with date and time In postgres SQL and want one row of each groupby column

I want to fetch data from history table and I want to group by usergroupid and I want only one row of usergroupid 237935 and 761793 out of multiple rows.我想从历史表中获取数据,我想按usergroupid分组,我只想要多行中的一行 usergroupid 237935 和 761793。

I get this error我收到这个错误

Column "history.entrytime" must appear in the GROUP BY clause or be used in an aggregate function “history.entrytime”列必须出现在 GROUP BY 子句中或用于聚合 function

This is my query:这是我的查询:

SELECT  
    TO_CHAR(entrytime, 'YYYY-MM-DD HH12:MI'), usergroupid 
FROM 
    "public"."history" 
WHERE 
    deviceid = 17355763  usergroupid IN (237935,761793) 
GROUP BY 
    TO_CHAR(entrytime, 'YYYY-MM-DD HH12:MI'), usergroupid 
ORDER BY
    entrytime DESC 
LIMIT 1

I want following output:我想关注 output:

to_char to_char usergroupid用户组id
2022-11-19 02:04:10 2022-11-19 02:04:10 237935 237935
2022-11-19 02:05:40 2022-11-19 02:05:40 761793 761793

This is my demo table:这是我的演示表:

在此处输入图像描述

It seems you simply want the maximum entrytime per usergroupid.看来您只是想要每个用户组 ID 的最大进入时间。 In order to get one row per usergroupid, you GROUP BY usergroupid .为了每个 usergroupid 获得一行,您GROUP BY usergroupid In order to get the maximum entrytime, you select MAX(entrytime) .为了获得最大的进入时间,你 select MAX(entrytime)

SELECT  MAX(entrytime), usergroupid
FROM public.history
WHERE deviceid = 17355763 AND usergroupid IN (237935,761793) 
GROUP BY usergroupid
ORDER BY usergroupid;

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

相关问题 我想根据 postgres sql 中给定的容差对时间间隔进行分组 - I want to group time interval based on given tolerance in postgres sql sql 中的一个问题,我想要当前日期/时间的下一分钟 - one issue in sql,i want next minute of current date/time 我希望 SQL 查询关联两个表数据,其中两个表各只有一列 - I want SQL query to relate two tables data ,where both tables have only one column each 我想根据一列在一行中总结我的 output - I want to summarize my output in a single row based on one column 我想根据 postgres sql 中的给定容差对时间间隔进行分组(对于连续时间间隔,请考虑 1 秒的间隔) - I want to group time interval based on given tolerance in postgres sql(consider interval of 1 sec for for continuous time interval) 我想在我的表中添加新行,但我想使用列名 (SQL) 进行数学运算 - I want to add new row in my table but I want to do mathematical operation using column names (SQL) 我想要具有特定日期duration的数据。我的SQL数据库 - I want data with a particular date duration.my database in sql 我想在 SQL 中将行值查询为列 - I want to query the row values as Column in SQL 我想在每个相同的日期汇总数据 - I want to aggregate data each same date 我想在每次更新或在SQL Server中插入行时获取当前日期时间 - I want to get the current date time every time I update or insert a row in SQL Server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM