PostgreSQL,Groupwise Min和Max值

时间:2015-09-04 15:18:49

标签: sql postgresql

我有一张像;

的桌子
CREATE TABLE public.user_locations
(
  id integer NOT NULL DEFAULT nextval('user_locations_id_seq'::regclass),
  user_id integer,
  created_at timestamp without time zone,
  location geography(Point,4326),
  cluster_id integer,
  CONSTRAINT user_locations_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);

CREATE INDEX index_user_locations_on_location
  ON public.user_locations
  USING gist
  (location);

CREATE INDEX index_user_locations_on_user_id
  ON public.user_locations
  USING btree
  (user_id);

我希望为特定用户获取每个群集的最小和最大created_at值。这样我就可以看到用户在群集中呆了多长时间。

目前我这样做;

SELECT * FROM (
  (
    SELECT DISTINCT ON (cluster_id) * FROM user_locations 
    WHERE user_id = 6
    ORDER BY cluster_id, created_at DESC
  )
  UNION
  (
    SELECT DISTINCT ON (cluster_id) * FROM user_locations 
    WHERE user_id = 6
    ORDER BY cluster_id, created_at ASC
  )
) a
ORDER BY cluster_id, created_at

我认为这不是一个好的解决方案。这是我的问题的正确查询?如果没有,您能否建议更好的方法来检索特定用户的每个群集的最小值和最大值?

1 个答案:

答案 0 :(得分:2)

这是窗口函数的用途:

  select id, user_id, cluster_id, location, 
         created_at, 
         min(created_at) over (partition by cluster_id) as min_created,
         max(created_at) over (partition by cluster_id) as max_created
  from user_locations
  where user_id = 6
  order by cluster_id, created_at