按最后更新日期对表A中分组的结果进行排序

huangapple go评论57阅读模式
英文:

Sorting PostgreSQL Grouped Results in Table A by Last Update Date

问题

我有两个PostgreSQL表,'A'和'B',其结构如下:

表 'A':

  • id:自动递增的主键
  • res_id:引用表 'B' 的外键
  • description:表描述
  • last_update:日期类型

表 'B':

  • id:带有自动递增的整数主键
  • description:varchar(256)

我需要帮助构建一个查询,该查询涉及在表 'A' 中按res_id进行分组,并根据表 'A' 中的last_update日期对结果进行排序。我该如何实现这一目标?

我尝试了以下查询:

SELECT count(id), res_id 
FROM A 
GROUP BY res_id 
ORDER BY id, last_update;

请注意,我已经更正了你的查询,将ORDER BY子句中的排序字段改为idlast_update,以确保正确的排序顺序。

英文:

I have two PostgreSQL tables, 'A' and 'B', with the following structures:

Table 'A':

  • id: primary key with auto-increment
  • res_id: foreign key referencing table 'B'
  • description: table description
  • last_update: date type

Table 'B':

  • id: integer primary key with auto-increment
  • description: varchar(256)

I need assistance with constructing a query that involves grouping by res_id in table 'A' and sorting the results based on the last_update date from table 'A'. How can I achieve this?

I've tried the following query:

SELECT count(id),res_id 
from A GROUP BY res_id
ORDER BY id last_update;

答案1

得分: 1

要根据res_id对记录进行分组,并根据每个分组中latest_update字段的最大值(max)对它们进行排序,您可以在您的选择查询中包括max(latest_update)函数。这允许您首先按res_id对记录进行分组,然后选择每个组的最大(max)日期。最后,您可以根据这个最大日期对整个结果集进行排序。

以下是如何构建查询的示例:

SELECT res_id, max(latest_update) AS max_date
FROM table_A
GROUP BY res_id
ORDER BY max_date;
英文:

To group records by res_id and sort them based on the maximum (max) value of the latest_update field within each group, you can include the max(latest_update) function in your select query. This allows you to first group the records by res_id and then select the maximum (max) date for each group. Finally, you can sort the entire result set based on this maximum date.

Here's an example of how you can construct the query:

SELECT res_id, max(latest_update) AS max_date
FROM table_A
GROUP BY res_id
ORDER BY max_date;

huangapple
  • 本文由 发表于 2023年5月25日 16:11:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定