gpt4 book ai didi

sql - PostgreSQL - "DISTINCT ON"和 "GROUP BY"语法

转载 作者:行者123 更新时间:2023-11-29 11:13:05 24 4
gpt4 key购买 nike

我意识到数据库查询返回了意外的结果,这与我对“DISTINCT ON”和“GROUP BY”的不当使用有关

我希望有人可以让我明白这一点。实际查询非常复杂,所以我将其简化:

我有一个由 object_id 和时间戳组成的表/内部查询:

CREATE TABLE test_select ( object_id INT , event_timestamp timestamp );
COPY test_select (object_id , event_timestamp) FROM stdin (DELIMITER '|');
1 | 2013-01-27 21:01:20
1 | 2012-06-28 14:36:26
1 | 2013-02-21 04:16:48
2 | 2012-06-27 19:53:05
2 | 2013-02-03 17:35:58
3 | 2012-06-14 20:17:00
3 | 2013-02-15 19:03:34
4 | 2012-06-13 13:59:47
4 | 2013-02-23 06:31:16
5 | 2012-07-03 01:45:56
5 | 2012-06-11 21:33:26
\.

我正在尝试选择一个不同的 ID,按反向时间戳进行排序/去重

所以结果应该是 [ 4, 1, 3, 2, 5 ]

我认为这满足了我的需要(似乎是):

SELECT object_id  
FROM test_select
GROUP BY object_id
ORDER BY max(event_timestamp) DESC
;

出于测试/审计目的,有时我想包含时间戳字段。我似乎无法弄清楚如何在该查询中包含另一个字段。

谁能指出我上面的 sql 中明显的问题,或者关于如何包含审计信息的建议?

最佳答案

要能够选择所有列而不仅仅是 object_idMAX(event_timestamp),您可以使用 DISTINCT ON

SELECT DISTINCT ON (object_id) 
object_id, event_timestamp ---, more columns
FROM test_select
ORDER BY object_id, event_timestamp DESC ;

如果您希望结果按 event_timestamp DESC 而不是按 object_id 排序,则需要将其包含在派生表或 CTE 中:

SELECT *
FROM
( SELECT DISTINCT ON (object_id)
object_id, event_timestamp ---, more columns
FROM test_select
ORDER BY object_id, event_timestamp DESC
) AS t
ORDER BY event_timestamp DESC ;

或者,您可以使用窗口函数,例如 ROW_NUMBER():

WITH cte AS
( SELECT ROW_NUMBER() OVER (PARTITION BY object_id
ORDER BY event_timestamp DESC)
AS rn,
object_id, event_timestamp ---, more columns
FROM test_select
)
SELECT object_id, event_timestamp ---, more columns
FROM cte
WHERE rn = 1
ORDER BY event_timestamp DESC ;

或聚合 MAX()OVER:

WITH cte AS
( SELECT MAX(event_timestamp) OVER (PARTITION BY object_id)
AS max_event_timestamp,
object_id, event_timestamp ---, more columns
FROM test_select
)
SELECT object_id, event_timestamp ---, more columns
FROM cte
WHERE event_timestamp = max_event_timestamp
ORDER BY event_timestamp DESC ;

关于sql - PostgreSQL - "DISTINCT ON"和 "GROUP BY"语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com